5

I have a snippet of JSON that looks like this:

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

The 123 is an ID and can change on each request. This is beyond my control.

I want to Deserialize the JSON using JSON.NET. I have tried:

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

However, this does not work unless I define the JsonProperty attribute like so:

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

But of course I cannot actually do this because the ID 123 will change on every request.

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

Barry Kaye
  • 7,682
  • 6
  • 42
  • 64
  • 1
    It would work with a `KeyValuePair`. You could try deserializing it in a temporary `object` buffer and then map it to your `User` instance. – Andrei V Jun 15 '15 at 13:11
  • 2
    It's not malformed; just awkwardly formed. Basically it's a KVP of where user has properties 'name' and 'info' – Dave Lawrence Jun 15 '15 at 13:15
  • I thought , In your class structure must be defined first class RootObject . In class Rootobject , u have to declare all json attribute as get set method. – Anurag Jain Jun 15 '15 at 13:16
  • 1
    As pointed out, `KeyValuePair` does not work. Using a `Dictionary` instead, as per @YuvalItzchakov's answer, will do the trick. – Andrei V Jun 15 '15 at 13:25

3 Answers3

5

Try this:

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

This does have some unnecessary overhead, but considering the circumstances, it would do.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
2

I'd do it this way:

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
}
stefankmitph
  • 3,236
  • 2
  • 18
  • 22
0

How about having JSON formed as follows (if at all changing JSON schema is allowed):

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

This way it must be possible.

Mahesha999
  • 22,693
  • 29
  • 116
  • 189