0

I have read some articles but didnt fix my problem , i have a problem with JSON string when deserialize, here the string

{"table":"sy_version","effected":2,"data":[{"mod_id":"CS","sub_mod":"sbm_sl.exe","version":"2015.11.07.1","upload_date ":"2015-11-10 11:34:13"},{"mod_id":"FA","sub_mod":"sbm_fa.exe","version":"2015.11.09","upload_date ":"2015-11-10 11:34:13"}]}    

And this is my class

    public class Datum
    {
        public string mod_id { get; set; }
        public string sub_mod { get; set; }
        public string version { get; set; }
        public DateTime upload_date { get; set; }
    }

    public class sy_periode
    {
        public string table { get; set; }
        public int effected { get; set; }
        public IList<Datum> datas { get; set; }
    }

    public static void test(string str) {
        // dynamic sy_periode = JsonConvert.DeserializeObject(str);
        var sy_periode = JsonConvert.DeserializeObject<sy_periode>(str);
        foreach (var data in sy_periode.datas)
        {
            Console.WriteLine(data.sub_mod);
        }

    }

When I executed, string table and effected have value, but datas is null, this is the error message

Object reference not set to an instance of an object.
1
  • Use the IDEs built in debugger; it's a lot quicker than using StackOverflow as a debugger. Even a quick look over the code would pick up the typo :) Commented Nov 20, 2015 at 8:49

1 Answer 1

2

It shouldn't be datas, it should have the same name as JSON object: data.

Here is the correct classes structure:

public class Datum
{
    public string mod_id { get; set; }
    public string sub_mod { get; set; }
    public string version { get; set; }
    public DateTime upload_date { get; set; }
}

public class sy_periode
{
    public string table { get; set; }
    public int effected { get; set; }
    public IList<Datum> data { get; set; }
}    

Also, note that in JSON your upload_date properties have an odd whitespace in the end: upload_date. It may be a typo. However, if it is an actual input and since C# member name cannot contain spaces, you can try to specify the name in order to serialize it:

[JsonProperty(PropertyName = "upload_date ")]
public DateTime upload_date { get; set; }

I am not quite sure that it will work, but I see no reasons of why it shouldn't.

Sign up to request clarification or add additional context in comments.

1 Comment

That it is, Thanks for your help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.