Removing Deserialized JSON Errors Using JSON.NET

I have a JSON snippet that looks like this:

{"123":{"name":"test","info":"abc"}} 

123 is an identifier and may change with every request. This is uncontrollable.

I want to deserialize JSON using JSON.NET. I tried:

  User u = JsonConvert.DeserializeObject<User>(json); 

However, this does not work if I do not define the JsonProperty attribute JsonProperty this:

 [JsonProperty("123")] public string ID { get; set; } 

But, of course, I can’t do this, because ID 123 will change with every request.

How can I read the ID property using JSON.NET and apply it to the ID class?

+5
source share
3 answers

Try the following:

 var json = "{\"123\":{\"name\":\"test\",\"info\":\"abc\"}}"; var rootObject = JsonConvert.DeserializeObject<Dictionary<string, User>>(json); var user = rootObject.Select(kvp => new User { ID = kvp.Key, Name = kvp.Value.Name, Info = kvp.Value.Info }).First(); 

It has some extra overhead, but given the circumstances, it will do.

+4
source

I would do it like this:

 dynamic result = JsonConvert.DeserializeObject(json); var myObject = result as JObject; var properties = myObject.Properties(); var property = properties.FirstOrDefault(); // take first element string name = property.Name; foreach (var item in properties) { var jProperty = item as JProperty; var nestedJson = jProperty.Value.ToString(); dynamic nestedResult = JsonConvert.DeserializeObject(nestedJson); // or put it into a model/data structure } 
+1
source

How about JSON being formed as follows (if JSON schema changes are allowed at all):

 { "ID": "123", "Properties":{"name":"test","info":"abc"} } 

Therefore, it should be possible.

0
source

All Articles