0

I have the following JSON data:

{
    "count": 2,

    "data" : {
        "items" : [
            {
                "id" : "1",
                "letterheadline" : "This is a test",
                "message" : "testing.. testing..",
                "dateEntered" : "2018-01-01 18:00"
            },

            {
                "id" : "2",
                "letterheadline" : "Message two",
                "message" : "testing.. testing.. testing..",
                "dateEntered" : "2018-02-01 18:00"
            },


        ]
    }

}

I am trying to parse it into my own object that uses different values, i.e:

public class Message 
{
    public string title {get; set;}

    public string body {get; set;}

    public DateTime entryDate {get; set;}
}

public class Messages
{
    public int itemCount {get; set;}

    public List<Message> messages {get; set}
}

I am using

Messages messages = new JavaScriptSerializer().Deserialize<Messages>(result);

I have tried to use the following:

[JsonProperty("letterheadline")] (for example)

But I am still getting an error saying that it cannot be converted.

Is this because the JSON data itself is too deep to parse? Therefore would I need to create a new property Data inside my object that contains a list of Messages?

5
  • Possible duplicate of Deserializing a JSON file with JavaScriptSerializer() Commented May 19, 2018 at 0:18
  • 3
    [JsonProperty] is for JSON.NET (NewtonSoft.Json), JavaScriptSerializer is the old, deprecated, built-in JSON library. Use the one you want, but don't mix them Commented May 19, 2018 at 0:23
  • @Attersson - thanks I get that and I understand the concept but will I need to create another property for "data" which contains a list of "items"? What type would data be? Also how will I map the field names to the one in my class as they are not the same?? Commented May 19, 2018 at 1:58
  • Did you try using Newsoft.JSON ? Commented May 19, 2018 at 4:19
  • Try auto-generating your data model using one of the tools from How to auto-generate a C# class file from a JSON object string. [JsonProperty("letterheadline")] is a json.net attribute, it doesn't work for JavaScriptSerializer as explained in JavaScriptSerializer - custom property name. Commented May 19, 2018 at 8:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.