Search code examples
c#json.netjson-deserialization

JArray Deserialize only first property value to Object


I have this json file:

[
    {
        "blah" : "some text here",
        "hidden" : false,
    },
    {
        "blah" : "some other text",
        "hidden" : false,
    }
]

I load it into a JArray and then I want to use to ToObject method to deserialize the data to a custom Class:

public class LookupItem
{
    public string DisplayMember { get; set; }
}

the display member I want it to be the value of the first property that appears on the objects. So that:

var a = myJArray.ToObject(List<LookupItem>);

would return

a[0].DisplayMember  --->  some text here
a[1].DisplayMember  --->  some other text

I thought I could use a

[JsonProperty(Order = 0)]

attribute but it doesn't seem to be working for deserialization only for serialization. (the real issue is that I don't know the first property's key value upfront).


Solution

  • Inconsitent JSON

    If there is no consistency in your JSON, you can deserialize the whole thing to an object.

    var items = JsonConvert.DeserializeObject("Your JSON"));
    

    Then cast it to a JContainer and loop through it and create your LookupItem objects. Code below assumes the first property is what you want:

    var luItems = new List<LookupItem>();
    var item = ((Newtonsoft.Json.Linq.JContainer)items).ToList()[0];
    ((Newtonsoft.Json.Linq.JContainer)items).ToList().ForEach(x => 
        luItems.Add(new LookupItem { DisplayMember = x.First.First().ToString() }));
    

    Consitent

    If there is consitency, then create a C# class to represent objects of your JSON:

    public class Class1
    {
        public string blah { get; set; }
        public bool hidden { get; set; }
    }
    

    Then deserialize and create LookupItem instances:

    var consitentItems = JsonConvert.DeserializeObject<Class1[]>(File.ReadAllText("Files/Json.txt"));
    var consistentLookupItems = new List<LookupItem>();
    consitentItems.ToList().ForEach(x => 
        consistentLookupItems.Add(new LookupItem { DisplayMember = x.blah }));