Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deserialize a JSON array and ignore the root node?

Tags:

I have next response from server -

{"response":[{"uid":174952xxxx,"first_name":"xxxx","last_name":"xxx"}]} 

I am trying to deserialize this in next way -

JsonConvert.DeserializeObject<T>(json);   

Where T = List of VkUser, but I got error.

[JsonObject] public class VkUser {     [JsonProperty("uid")]     public string UserId { get; set; }      [JsonProperty("first_name")]     public string FirstName { get; set; }      [JsonProperty("last_name")]     public string LastName { get; set; } } 

I always tryed

public class SomeDto // maybe Response as class name will fix it but I don't want such name {     public List<VkUser> Users {get;set;} } 

What deserialization options can help me?

like image 441
tony Avatar asked Jan 06 '14 15:01

tony


People also ask

How do I ignore a root element in JSON?

How to ignore parent tag from json?? String str = "{\"parent\": {\"a\":{\"id\": 10, \"name\":\"Foo\"}}}"; And here is the class to be mapped from json. (a) Annotate you class as below @JsonRootName(value = "parent") public class RootWrapper { (b) It will only work if and only if ObjectMapper is asked to wrap.

How do I deserialize JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

How does JSON deserialize work?

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.


1 Answers

Use SelectToken:

string s =  "{\"response\":[{\"uid\":174952,\"first_name\":\"xxxx\",\"last_name\":\"xxx\"}]}";  var users = JObject.Parse(s).SelectToken("response").ToString();  var vkUsers = JsonConvert.DeserializeObject<List<VkUser>>(users); 

as pointed out by Brian Rogers, you can use ToObject directly:

var vkUsers = JObject.Parse(s).SelectToken("response").ToObject<List<VkUser>>(); 
like image 199
Alberto Avatar answered Oct 06 '22 02:10

Alberto