Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

c# - How to parse this JSON using Newton Soft for nested object

How to parse this JSON

using Newton Soft

I tried but gives me null as my modal should have class 1, 2, 3 ... but that's dynamic .So getting confuse.

Appreciate your help !

{
"data": {
    "1": {
        "test": {
            "col1": "123",
            "col2": "name"
        }
    },
    "2": {
        "test": {
            "col1": "345",
            "col2": "name2"
        }
    },
    "3": {
        "test": {
            "col1": "456",
            "col2": "name3"
        }
    }
}
class root 
{ 
    data data{get; set;};
}

class data
{ 
    List<object> innerObject {get; set;} //not sure as labels are dynamic 
} 

class test
{ 
    col1{get; set;} 
    col2{get; set;} 
} //Calling it in that way .. 

root r = JsonConvert.DeserializeObject<root>(result);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a dictionary to parse a JSON object with custom property names:

public class Test
{
    public string col1 { get; set; }
    public string col2 { get; set; }
}

public class DataValue
{
    public Test test { get; set; }
}

public class RootObject
{
    public RootObject() { this.data = new Dictionary<string, DataValue>(); }
    public Dictionary<string, DataValue> data { get; set; }
}

See Deserialize a Dictionary.

If you are sure the dictionary keys will always be numeric, you can use integer keys, and use a SortedDictionay to order the values:

public class RootObject
{
    public RootObject() { this.data = new SortedDictionary<long, DataValue>(); }
    public SortedDictionary<long, DataValue> data { get; set; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...