2

I need a little help with json deserialization. It's the first time I'm using Json, so I have just a little knowledge about it.

I get the following string using a webclient:

[{"name": "somename", "data": [[72, 1504601220], [null, 1504601280], ..., [125, 1504605840]]}]

and tried to serialize it with

JsonConvert.DeserializeObject<TestObject>(jsonstring)

My class looks like this:

public class TestObject
{
    [JsonProperty(PropertyName = "name")]
    public string TargetName { get; set; }

    [JsonProperty(PropertyName = "data"]
    public List<?????> DataPoints {get; set;}
}

How do I need to design my class to get the data values in some kind of collection so each entry contains the two values inside a bracket?

Thx for your patience and help!

3 Answers 3

9

Your data is a list of arrays containing nullable integers (by the looks of it)

[JsonProperty(PropertyName = "data"]
public List<int?[]> DataPoints {get; set;}
Sign up to request clarification or add additional context in comments.

3 Comments

This looked promising, but I got a JsonSerializationException ("Cannot deserialize the current JSON array [...] because the type requires a JSON object [...] to deserialize correctly.")
@ErikT. Looks like youve copied some JSON string from the console which includes this char (...) instead of the real actual JSON text. See this live example for it working without that character: rextester.com/ESC67816
Stupid me used <TestObject> insead of <List<TestObject>>. It's working properly now. Thanks!
2

Try this website: http://json2csharp.com/ This website can save a lot of your time if you have just a plain JSON text. It helps you convert it to C# object, although you still have to double check it.

var data = "[{\"name\": \"somename\", \"data\": [[72, 1504601220], [null, 1504601280], [125, 1504605840]]}]";
var obj = JsonConvert.DeserializeObject<List<TestObject>>(data);

public class TestObject
{
    [JsonProperty(PropertyName = "name")]
    public string TargetName { get; set; }
    [JsonProperty(PropertyName = "data")]
    public List<int?[]> DataPoints { get; set; }
}

1 Comment

Thank you for that website recommendation. Seems pretty useful, especially for larger strings.
0

There is a some solution for this, C# 7.0 also supports ValueTuple such as this example.

List<(int? ,int?)> DataPoints { get; set; }
// if it not work try this.
List<List<int?>> DataPoints { get; set; }

If your json inner array elements count is equal to 2, so can assume to you use the value tuples.

Assume it is helpful for you.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.