简体   繁体   中英

Generating C# classes from JSON key value pair

I have been searching for a solution for a few hours now but haven't found anything that explains my problem. I am an absolute beginner in C# and I need help converting this JSON into C# classes, particularly the fields object that has a key value pair.

Here is what the JSON looks like:

[
 {
   "creationTimestamp": 1485384284523,
   "lastUpdatedTimestamp": 1485384699883,
   "lastStageChangeTimestamp": 1485384284523,
   "fields": {
       "key1": "val1",
       "key2": "val2"
    }
 }
]

Any tips on how to approach this problem would be highly appreciated. Thank you!

Create a class to hold the data.

Using a tool like http://jsonutils.com/ you can paste the json and get back

public class Fields
{
    public string key1 { get; set; }
    public string key2 { get; set; }
}

public class RootObject
{
    public long creationTimestamp { get; set; }
    public long lastUpdatedTimestamp { get; set; }
    public long lastStageChangeTimestamp { get; set; }
    public Fields fields { get; set; }
}

The Json.Net library would allow you to desrialize the json into the above classes.

var models = JsonConvert.DesrializeObject<RootObject[]>(json);

var val1 = models[0].key1;
var val2 = models[0].key2;
Please Use Dictionary datatype for fields property
public class RootObject
{
 public long creationTimestamp { get; set; }
 public long lastUpdatedTimestamp { get; set; }
 public long lastStageChangeTimestamp { get; set; }
 public Dictionary<string,string> fields { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM