40

I have a JSON string and I need some help to deserialize it.

Nothing worked for me... This is the JSON:

{
    "response": [{
        "loopa": "81ED1A646S894309CA1746FD6B57E5BB46EC18D1FAff",
        "drupa": "D4492C3CCE7D6F839B2BASD2F08577F89A27B4ff",
        "images": [{
                "report": {
                    "nemo": "unknown"
                },
                "status": "rock",
                "id": "7e6ffe36e-8789e-4c235-87044-56378f08m30df",
                "market": 1
            },
            {
                "report": {
                    "nemo": "unknown"
                },
                "status": "rock",
                "id": "e50e99df3-59563-45673-afj79e-e3f47504sb55e2",
                "market": 1
            }
        ]
    }]
}

I have an example of the classes, but I don't have to use those classes. I don't mind using some other classes.

These are the classes:

public class Report
{
    public string nemo { get; set; }
}

public class Image
{
    public Report report { get; set; }
    public string status { get; set; }
    public string id { get; set; }
    public int market { get; set; }
}

public class Response
{
    public string loopa { get; set; }
    public string drupa{ get; set; }
    public Image[] images { get; set; }
}

public class RootObject
{
    public Response[] response { get; set; }
}

I want to mention that I have Newtonsoft.Json already, so I can use some functions from there.

How can I do this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Assaf Zigdon
  • 461
  • 2
  • 5
  • 9

12 Answers12

48

I am using like this in my code and it's working fine

below is a piece of code which you need to write

using System.Web.Script.Serialization;

JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);
Javal Patel
  • 838
  • 7
  • 12
45

Should just be this:

var jobject = JsonConvert.DeserializeObject<RootObject>(jsonstring);

You can paste the json string to here: http://json2csharp.com/ to check your classes are correct.

stevepkr84
  • 1,637
  • 2
  • 13
  • 23
  • i tried this, but i am only getting "The name 'does not exist in the current context" when entering to the quick view – Assaf Zigdon May 02 '13 at 13:37
  • Did you try classes as per the website I linked? I see they are different in that they use List rather than arrays in the RootObject and Response classes. Not sure if it would make a difference. – stevepkr84 May 02 '13 at 13:41
  • yes, i changed it for a test, but the original was from this site – Assaf Zigdon May 02 '13 at 13:52
21

If you use C# 2010 or newer, you can use dynamic type:

dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstring);

Then you can access attributes and arrays in dynamic object using dot notation:

string nemo = json.response[0].images[0].report.nemo;
filipko
  • 955
  • 5
  • 16
  • Could have been a good idea, but not working for me: **One or more types required to compile a dynamic expression cannot be found. Are you missing a reference** – Allen Linatoc Jul 06 '15 at 13:11
9

First install newtonsoft.json package to Visual Studio using NuGet Package Manager then add the following code:

ClassName ObjectName = JsonConvert.DeserializeObject < ClassName > (jsonObject);
Dmitry Pavlov
  • 30,789
  • 8
  • 97
  • 121
Tejas Jain
  • 162
  • 1
  • 8
4

I had a scenario, and this one helped me

JObject objParserd = JObject.Parse(jsonString);

JObject arrayObject1 = (JObject)objParserd["d"];

D myOutput= JsonConvert.DeserializeObject<D>(arrayObject1.ToString());

Ozesh
  • 6,536
  • 1
  • 25
  • 23
4

shareInfo is Class:

public class ShareInfo
        {
            [JsonIgnore]
            public readonly DateTime Timestamp = DateTime.Now;
            [JsonProperty("sharename")]
            public string ShareName = null;
            [JsonProperty("readystate")]
            public string ReadyState = null;
            [JsonProperty("created")]
            [JsonConverter(typeof(Newtonsoft.Json.Converters.UnixDateTimeConverter))]
            public DateTime? CreatedUtc = null;
            [JsonProperty("title")]
            public string Title = null;
            [JsonProperty("getturl")]
            public string GettUrl = null;
            [JsonProperty("userid")]
            public string UserId = null;
            [JsonProperty("fullname")]
            public string Fullname = null;
            [JsonProperty("files")]
            public GettFile.FileInfo[] Files = new GettFile.FileInfo[0];
        }

// POST request.
            var gett = new WebClient { Encoding = Encoding.UTF8 };
            gett.Headers.Add("Content-Type", "application/json");
            byte[] request = Encoding.UTF8.GetBytes(jsonArgument.ToString());
            byte[] response = gett.UploadData(baseUri.Uri, request);

            // Response.
            var shareInfo = JsonConvert.DeserializeObject<ShareInfo>(Encoding.UTF8.GetString(response));
Veera Induvasi
  • 822
  • 7
  • 19
3
 public static void Main(string[] args)
{
    string json = @" {
    ""children"": [
            {
        ""url"": ""foo.pdf"", 
                ""expanded"": false, 
                ""label"": ""E14288-Passive-40085-2014_09_26.pdf"", 
                ""last_modified"": ""2014-09-28T11:19:49.000Z"", 
                ""type"": 1, 
                ""size"": 60929
            }
        ]
     }";




    var result = JsonConvert.DeserializeObject<ChildrenRootObject>(json);
    DataTable tbl = DataTableFromObject(result.children);
}

public static DataTable DataTableFromObject<T>(IList<T> list)
{
    DataTable tbl = new DataTable();
    tbl.TableName = typeof(T).Name;

    var propertyInfos = typeof(T).GetProperties();
    List<string> columnNames = new List<string>();

    foreach (PropertyInfo propertyInfo in propertyInfos)
    {
        tbl.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
        columnNames.Add(propertyInfo.Name);
    }

    foreach(var item in list)
    {
        DataRow row = tbl.NewRow();
        foreach (var name in columnNames)
        {
            row[name] = item.GetType().GetProperty(name).GetValue(item, null);
        }

        tbl.Rows.Add(row);
    }

    return tbl;
}

public class Child
{
    public string url { get; set; }
    public bool expanded { get; set; }
    public string label { get; set; }
    public DateTime last_modified { get; set; }
    public int type { get; set; }
    public int size { get; set; }
}

public class ChildrenRootObject
{
    public List<Child> children { get; set; }
}
  • 1
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – kayess Dec 01 '16 at 08:30
2

I also had the issue of parsing and using JSON objects in C#. I checked the dynamic type with some libraries, but the issue was always checking if a property exists.

In the end, I stumbled upon this web page, which saved me a lot of time. It automatically creates a strongly typed class based on your JSON data, that you will use with the Newtonsoft library, and it works perfectly. It also works with languages other than C#.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
davidthegrey
  • 1,205
  • 2
  • 14
  • 23
  • But will that handle the irregular types in this particular JSON (in the question). Have you actually tried to run it? – Peter Mortensen Apr 18 '19 at 22:03
  • It handles missing json properties quite well (it will automatically convert to nullable types when it recognises properties not repeated in the arrays of objects). Of course having a c# converter class would not make sense if the json was completely irregular/randomic. In those situations, using dynamic is the way to go. In complex situations, like the project I am working on, I had to make some minor manual adjustments, eg converting some integer types to decimal (if the sample you submit does not contain fractional figures), manually adding nullables, ... – davidthegrey Apr 27 '19 at 12:25
1

I am using following:

    using System.Web.Script.Serialization;       

    ...

    public static T ParseResponse<T>(string data)
    {
        return new JavaScriptSerializer().Deserialize<T>(data);
    }
Uzzy
  • 550
  • 3
  • 14
1

I solved this problem to add a public setter for all properties, which should be deserialized.

everydayXpert
  • 785
  • 2
  • 11
  • 27
1

You can solve your problem like below bunch of codes

public class Response
{
    public string loopa { get; set; }
    public string drupa{ get; set; }
    public Image[] images { get; set; }
}

public class RootObject<T>
    {
        public List<T> response{ get; set; }

    }

var des = (RootObject<Response>)Newtonsoft.Json.JsonConvert.DeserializeObject(Your JSon String, typeof(RootObject<Response>));
Mahdi ghafoorian
  • 1,147
  • 10
  • 8
0

You could use the nuget package Newtonsoft.JSON in order to achieve this:

JsonConvert.DeserializeObject<List<Response>>(yourJsonString)
Twenty
  • 5,234
  • 4
  • 32
  • 67
  • 2
    Welcome to Stack Overflow. Perhaps some [clearer formatting](https://stackoverflow.com/help/formatting) could help improve your answer. – Ann Kilzer Dec 04 '19 at 13:38