3

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
  • 1
    json2csharp.com will be your friend. It creates classes and members according to a JSON String. It saves a lot time! Commented May 1, 2012 at 20:23

3 Answers 3

6

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; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Mike_G OP doesn't use DataContractJsonSerializer either. I see only DataContractJsonSerializer ser = null; Is this the only explanation of your downvote for a working code ?
Yes, it works! Thanks a lot! If anybody need a string (like me) just put obj["name"].ToString(). Maybe it's something noob but, as I said, I'm new in C#!
1

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.

2 Comments

-1 Doesn't work since OP's json string is not an array or a List. Easy to test
Have overseen the need for a root class. @L.B: Thanks for pointing this out
1

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);

3 Comments

-1 Doesn't work since OP's json string is not an array or a List. Easy to test.
of course it doesnt work, its not a program lol. he wasnt wanting it done for him, he asked what to do next. As you can see, i demonstrated to two major components for completely his task. Lol, some people....
Your answer was trying to deserialize OP's json string to a List not to a root object and you say now of course it doesnt work. Good policy to answer. Just write anything random, since you don't expect it to run. LOL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.