DanielaTahnee
DanielaTahnee

Reputation: 5

Can't deserialize JSON string in C#

I receive the following JSON string from a 3rd party:

{
    "Ch": [{
        "i": 100,
        "m": "Time",
        "u": "(sec)",
        "d": 0,
        "z": 0.345313,
        "yi": "0.000000",
        "ya": "6.906250",
        "a": 0,
        "s": 1664,
        "data": "RN]]>"
    }, {
        "i": 101,
        "m": "Stress",
        "u": "(kPa)",
        "d": 0,
        "z": 60,
        "yi": "0.000000",
        "ya": "1200.000000",
        "a": 0
    }, {
        "i": 102,
        "m": "Strain",
        "u": "(micro e)",
        "d": 0,
        "z": 8,
        "yi": "200.000000",
        "ya": "360.000000",
        "a": 0
    }, {
        "i": 103,
        "m": "Stress",
        "u": 360,
        "d": 0,
        "z": 0,
        "yi": "0.000000",
        "ya": "0.000000",
        "a": 0,
        "s": 1664,
        "data": "QVORR`Pb_UQRR</code>OObTNRRUTaWRVRRSaPQPdRRaPNSORRR]]>"
    }, {
        "i": 104,
        "m": "Strain",
        "u": 360,
        "d": 0,
        "z": 0,
        "y": 0,
        "yi": "0.000000",
        "ya": "0.000000",
        "a": 1,
        "s": 1664,
        "data": "SVdRQSP_VWQRQa]]>"
    }]
}

I use the following classes:

public class testCh
{
    public int i { get; set; }
    public string m { get; set; }
    public object u { get; set; }
    public int d { get; set; }
    public double z { get; set; }
    public string yi { get; set; }
    public string ya { get; set; }
    public int a { get; set; }
    [JsonIgnore]
    public int s { get; set; }
    [JsonIgnore]
    public string data { get; set; }

}

public class testRootObject
{
    public List<testCh> tCh { get; set; }
}

And finally I try this in my main class:

var response1 = JsonConvert.DeserializeObject<testRootObject>(content1);

foreach (testCh tc in response1.tCh)
{
    string name = tc.m;
}

I do get an empty testRootObject[]

I've tried ignoring "a" and "data" in my testCH class:

[JsonIgnore]
public int s { get; set; }

[JsonIgnore]
public string data { get; set; }

and it didn't work.

I'm not sure why I can't deserialize it. It must be something silly but after trying for a couple days I can't see it.

Any help or hint is much appreciated.

Upvotes: 0

Views: 605

Answers (1)

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

I've checked this out and confirmed. The only error you got here is that the name of the list object. It should be Ch as in your json string.

public class testRootObject
{
    public List<testCh> Ch { get; set; }
}

If it is a must that that properties name should be tCh than you can do the following:

public class testRootObject
{
    [JsonProperty("Ch")]
    public List<testCh> tCh { get; set; }
}

Upvotes: 1

Related Questions