-2

Im having with the content. it is auto increment. the result is static but the content is dynamic.

I'm using a hardcoded array in catching the return string from the web. Can anyone json decoder in converting the returned string to c# object

This is the returned string from web:

{
   "result":{
      "count":"3"
   },
   "content_1":{
      "message_id":"23",
      "originator":"09973206870",
      "message":"Hello",
      "timestamp":"2016-09-14 13:59:47"
   },
   "content_2":{
      "message_id":"24",
      "originator":"09973206870",
      "message":"Test again.",
      "timestamp":"2016-09-14 14:49:14"
   },
   "content_3":{
      "message_id":"25",
      "originator":"09973206870",
      "message":"Another message",
      "timestamp":"2016-09-14 14:49:20"
   }
}
Itsumo Kokoro
  • 169
  • 4
  • 14
  • 2
    Possible duplicate of [Deserialize JSON with C#](http://stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp) – BWA Sep 14 '16 at 07:11
  • Have a look at [this](http://stackoverflow.com/a/35061662/5453249) answer – croxy Sep 14 '16 at 07:13

1 Answers1

1

On site json2csharp.com you can generate classes for JSON data. Generated classes needs some improvements and can look like:

public class Result
{
    public string count { get; set; }
}

public class Content
{
    public string message_id { get; set; }
    public string originator { get; set; }
    public string message { get; set; }
    public string timestamp { get; set; }
}    

public class RootObject
{
    public Result result { get; set; }
    public Content content_1 { get; set; }
    public Content content_2 { get; set; }
    public Content content_3 { get; set; }
}

And using JSON.NET you can deserialize it:

public class Program
{
    static public void Main()
    {
        string json = "{ \"result\":{ \"count\":\"3\" }, \"content_1\":{ \"message_id\":\"23\", \"originator\":\"09973206870\", \"message\":\"Hello\", \"timestamp\":\"2016-09-14 13:59:47\" }, \"content_2\":{ \"message_id\":\"24\", \"originator\":\"09973206870\", \"message\":\"Test again.\", \"timestamp\":\"2016-09-14 14:49:14\" }, \"content_3\":{ \"message_id\":\"25\", \"originator\":\"09973206870\", \"message\":\"Another message\", \"timestamp\":\"2016-09-14 14:49:20\" } }";

        RootObject ro = JsonConvert.DeserializeObject<RootObject>(json);

        Console.WriteLine(ro.content_1.message_id);
        Console.WriteLine(ro.content_2.message_id);                 
    }
}
Mikhail Tulubaev
  • 4,141
  • 19
  • 31
BWA
  • 5,672
  • 7
  • 34
  • 45
  • Hi sir, how do i deal if the content is auto increment? thank you – Itsumo Kokoro Sep 14 '16 at 08:04
  • If content is auto increment this is bad JSON design. In my opinion there should by array of content. But you can try `dynamic` as type of RootObject and dynamicly get properties. – BWA Sep 14 '16 at 08:24