Search code examples
c#jsonserializationdeserializationjson-deserialization

How to create Model Class of Json Object - c#


I have a Json object to which I want to bind to a model class. I have tried different ways of creating a class but the mapping deos not work and rootObj always return null properties, I think I am unable to generate a model according to the JSON string.

I am sharing two line code:

string serializedObj = JsonConvert.SerializeObject(nftList);
var rootObj = JsonConvert.DeserializeObject<List<Root>>(serializedObj);

My json string serializedObj is:

[
  {
    "json": "{\"Listing\": {\"Period\": 1209600, \"AssetID\": \"536d6f6f74685965746934333130\", \"Interest\": 1000, \"PolicyID\": \"eaa972045049185981aca9f4aaad38bc307776c593e4a849d3802a87\", \"Principal\": 300000000, \"BorrowerPKH\": \"ab77bec82618a2a5e8d891ad03361186a625861227605cb65f8ff312\"}, \"Deadline\": 1678360215, \"LenderPKH\": \"0b03d391a4746acf14794e4eaa531b67c25d69abed8512d0ecf35534\"}",
    "Principal": null
  },
  {
    "json": "{\"Listing\": {\"Period\": 1814400, \"AssetID\": \"424a533030393039\", \"Interest\": 600, \"PolicyID\": \"e282271ec9251ba23fb123b0f53618b35cf5a6cde4170c003a0ebf13\", \"Principal\": 70000000, \"BorrowerPKH\": \"155452c3bb66efa0e8493a018a2a16cdc7a5aaed1ae04020a2ef8dce\"}, \"Deadline\": 1679012316, \"LenderPKH\": \"e838596e09bee22eeb8615f6fc377582bab16ff9d961c6f74338c8ea\"}",
    "Principal": null
  }
]

I am trying Newton json


Solution

  • The problem is that your JSON contains nested JSON. A reasonable model of your actual JSON is:

    public class Root
    {
        [JsonProperty("json")]
        public string Json { get; set; }
    
        // TODO: Possibly use a different type; we can't tell what
        // it's meant to be
        [JsonProperty("Principal")]
        public string Principal { get; set; }
    }
    

    You might then have a different class with Listing (which looks like it needs another class containing Period) etc. I'll call this UsefulRoot for now. (Ideally you'd give it a more meaningful name.)

    To get from your original JSON to a List<UsefulRoot> you'd need to deserialize in two phases - once for the JSON objects represented at the top level, containing JSON, and then once for the Json property of each of them:

    var roots = JsonConvert.DeserializeObject<List<Root>>(serializedObj);
    var usefulRoots = roots
        .Select(root => JsonConvert.DeserializeObject<UsefulRoot>(root.Json))
        .ToList();