1

I have a JSON string that I am trying to parse, using C#. I have used JsonConvert to serialize my data into a JSON string.

Here is my sample JSON string:

{"names": ["John", "Joe", "Jack"], "nationality": "American"}

I am able to deserialize this string into an object using JsonConvert.DeserializeObject(x);

The problem is, I dont know how to read from the object, using C#. Can someone help me out?

6 Answers 6

1
public class People
{
  [JsonProperty("names")]
  public List<string> Names;

  [JsonProperty("nationality")]
  public string Nationality;
}

Other answers are technically correct, but using JsonPropertyAttribute is a universally accepted convention. Then use JsonConvert:

var people = JsonConvert.DeserializeObject<People>(x);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 I'm a fan of good documented code, even if JsonProperty is not required, I would know by looking at the object that it is used with Json Serialization, without reading other lines of code.
1

A better approach would be to define a class with the expected structure, then using JavaScriptSerializer to deserialize it:

class NameSet
{
    public IList<string> names { get; set; }
    public string nationality { get; set; }
}

var serializer = new JavaScriptSerializer();
var nameset  = serializer.Deserialize<NameSet>(jsonString);

Comments

1

Create a custom class like this:

public class CustomData
{
    public string[] Names { get; set; }
    public string Nationality { get; set; }

    public CustomData() { }
}

And use JsonConvert to deserialize yo an object of this type:

CustomData data = JsonConvert.DeserializeObject<CustomData>(x);

Comments

1

The following should suffice:

public class PeopleGroup {

    public string[] names { get; set; }
    public string nationality { get; set }

}

var myObject = JsonConvert.DeserializeObject<PeopleGroup>(x);

Basically, you create a strongly typed object, and deserialise directly into it.

Comments

1

If you don't want to actually define a class, you can use an anonymous type:

string json = "{\"names\": [\"John\", \"Joe\", \"Jack\"], \"nationality\": \"American\"}";

// Just defining the structure of the anonymous type
var x = new { names = new string[0], nationality = string.Empty };

x = JsonConvert.DeserializeAnonymousType(json, x);

5 Comments

Hi, just tried this and it worked perfectly. Just wanted to know if there is any advantage to using this method vs the "class" method, except for less code of course. Thanks
This solution is most writeable, but sacrifices readability. Which is more important to you depends on how many homicidal programmers you expect to review your code in the future.
@pat Two disadvantages. Minor: it creates an object that then gets thrown away again. Major: the object must be processed fully within that code block, which could lead to difficulties restructuring the code at a later date.
@LukeWillis and @AdrianWragg have great points. In my personal opinion, anonymous types make sense in a very limited scenario, only where a strong type is basically meaningless. For example, returning simple JSON objects (like {"success": false, "message": "Invalid Request"}) on an AJAX call in MVC might be ok. I'd expect the majority of the time, it's worth the effort to build a real class, especially if there's any possibility you'll be using that object outside of a very limited scope.
Thanks Guys, this little discussion really helped me out. Always think ahead and avoid writing code that seems quick to write for me and difficult for others or even me to read at a later date. Thanks again!
0

You should use dataContractJsonSerializer class, it is faster and most important is it is inbuilt class of .Net Framework. I will post solution in my next commment, in that How can we use DataContractJsonSerializer class.Now I cant post solution because in my end net is too slow :(, but I will post today.

Comments

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.