简体   繁体   中英

Retrieving data from an Object(deserialized json) in C#

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?

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

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

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM