Parsing JSON object containing an array with Windo

2019-02-18 14:48发布

问题:

Ok, I'm having some difficult with this.

My JSON is like

{ "names" : [ {"name":"bla"} , {"name":"bla2"} ] }

I was trying to do this tutorial but, due to the different JSON, it didn't worked.

What do I have to put inside this method? I don't know if it's better to create a "wrap" class that contain my list or using directly a JsonObject. Could you provide me a snippet? I'm kinda new in C#.

void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        DataContractJsonSerializer ser = null;
        try
        {
           ???
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Thanks in advance!

回答1:

Using Json.Net (which supports Windows Phone)

string json = @"{ ""names"" : [ {""name"":""bla""} , {""name"":""bla2""} ] }";

var dict = (JObject)JsonConvert.DeserializeObject(json);
foreach (var obj in dict["names"])
{
    Console.WriteLine(obj["name"]);
}

Or if you want to use it in a type-safe way

var dict = JsonConvert.DeserializeObject<RootClass>(json);
foreach (var obj in dict.names)
{
    Console.WriteLine(obj.name);
}


public class RootClass
{
    public MyName[] names { get; set; }
}

public class MyName
{
    public string name { get; set; }
}


回答2:

I'm using JSON.NET ( http://james.newtonking.com/projects/json-net.aspx ) normally, so my code might vary a bit.

For the list content I would go for a class with a name property like that:

public class NameClass {
    public string name { get;set; }
}

Then you should be able to deserialize with JSON.NET a List<NameClass>:

List<NameClass> result = JsonConvert.Deserialize<List<NameClass>>(jsonString);

This is written out of my head, so maybe, it doesn't compile with copy and paste, but it should work as a sample.



回答3:

Using the .NET DataContractJsonSerializer you will need to define a class that maps the json objects. Something like this (if i remember correctly):

/// <summary>
/// 
/// </summary>
[DataContract]
public class Result
{
    /// <summary>
    /// 
    /// </summary>
    [DataMember(Name = "name")]
    public string Name
    { get; set; }
}

 /// <summary>
/// 
/// </summary>
[DataContract]
public class Results
{
    /// <summary>
    /// 
    /// </summary>
    [DataMember(Name = "names")]
    public List<Result> Names
    { get; set; }
}

then in your event handler:

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Results));
var results = (Results)serializer.ReadObject(SOME OBJECT HOLDING JSON, USUALLY A STREAM);