Ho dei dati json che voglio analizzare in C #.
Json :
{
Key1 : 5,
Key2 : 6,
Array : [
{Id : 5} ,
{Id : 6} ,
{Id : 7} ,
...
]
}
Codice C #:
var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(jsonData);
var key1 = dict["Key1"];
var key2 = dict["Key2"];
var array = dict["Array"];
// array type is object { System.Collections.ArrayList }
con questo codice posso prendere i valori key1 e key2 ma non posso prendere i valori dell'array. Come posso analizzare i valori dell'array?
risposte:
0 per risposta № 1utilizzare questo metodo per analizzare la stringa json
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
0 per risposta № 2
Se fossi in me, avrei usato JSON.NET per deserializzare il JSON in un JObject, quindi puoi attraversare il modello a oggetti JSON che è più facile che forzarlo in un dizionario.
Il codice di parsing equivalente assomiglia a:
var json = JObject.Parse(jsonData)
JValue the_id_of_the_first_item_in_the_array_named_Array = ((JValue)json["Array"][0]["Id"]);
object the_underlying_value = the_id_of_the_first_item_in_the_array_named_Array.Value;
Esegui su .NET Fiddle: https://dotnetfiddle.net/mbmane
0 per risposta № 3
utilizzando dynamic
la parola chiave può rendere il tuo codice più leggibile
dynamic obj = JsonConvert.DeserializeObject(json);
int key1 = obj.Key1;
int key2 = obj.Key2;
foreach(var item in obj.Array)
{
int id = item.Id;
Console.WriteLine(id);
}
PS: richiede Json.Net