Parsing a JSON object containing an array with Windows Phone 7

Well, it's hard for me to handle this.

My JSON is like

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

I tried to make this tutorial , but due to different JSON, this did not work.

What do I need to do inside this method? I do not know if it is better to create a "wrap" class containing my list, or directly using JsonObject. Could you provide me a fragment? I am a little new to C #.

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

Thanks in advance!

+3
source share
3 answers

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 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; }
}
+6
source

JSON.NET(http://james.newtonking.com/projects/json-net.aspx), .

name:

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

JSON.NET a List<NameClass>:

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

, , , , .

+1

Using the .NET DataContractJsonSerializer, you will need to define a class that displays 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 the event handler:

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

All Articles