[c#] How to convert Json array to list of objects in c#

I have Json string like below

 {
"JsonValues":{

        "id": "MyID",

         "values": {
            "value1":{
                "id": "100",
                "diaplayName": "MyValue1"
            },
            "value2":{
                "id": "200",
                "diaplayName": "MyValue2"
            }
       }
}
}

I want to convert Json string to below classes

  class ValueSet
   {
    [JsonProperty("id")]
    public string id
    {
        get;
        set;
    }
    [JsonProperty("values")]
    public List<Value> values
    {
        get;
        set;
    }
  }

class Value
{
    public string id
    {
        get;
        set;
    }
    public string DiaplayName
    {
        get;
        set;
    }
}

My deserialization code is

JavaScriptSerializer js = new JavaScriptSerializer();
        StreamReader sr = new StreamReader(@"ValueSetJsonString.txt");
        string jsonString = sr.ReadToEnd();
        var items = JsonConvert.DeserializeObject<ValueSet>(jsonString);

But I am getting null values after serialization, How i can solve this?

This question is related to c# json json.net

The answer is


you have an unmatched jSon string, if you want to convert into a list, try this

{
    "id": "MyID",

     "values": [
        {
            "id": "100",
            "diaplayName": "MyValue1",
        },
        {
            "id": "200",
            "diaplayName": "MyValue2",
        }
   ]    
}

You may use Json.Net framework to do this. Just like this :

Account account = JsonConvert.DeserializeObject<Account>(json);

the home page : http://json.codeplex.com/

the document about this : http://james.newtonking.com/json/help/index.html#


This is possible too:

using System.Web.Helpers;
var listOfObjectsResult = Json.Decode<List<DataType>>(JsonData);

Json Convert To C# Class = https://json2csharp.com/json-to-csharp

after the schema comes out

        WebClient client = new WebClient();

        client.Encoding = Encoding.UTF8;

        string myJSON = client.DownloadString("http://xxx/xx/xx.json");

        var valueSet = JsonConvert.DeserializeObject<Root>(myJSON);

The biggest one of our mistakes is that we can't match the class structure with json.

This connection will do the process automatically. You will code it later ;) = https://json2csharp.com/json-to-csharp

that's it.


http://json2csharp.com/

I found the above link incredibly helpful as it corrected my C# classes by generating them from the JSON that was actually returned.

Then I called :

JsonConvert.DeserializeObject<RootObject>(jsonString); 

and everything worked as expected.


Your data structure and your JSON do not match.

Your JSON is this:

{
    "JsonValues":{
        "id": "MyID",
        ...
    }
}

But the data structure you try to serialize it to is this:

class ValueSet
{
    [JsonProperty("id")]
    public string id
    {
        get;
        set;
    }
    ...
}

You are skipping a step: Your JSON is a class that has one property named JsonValues, which has an object of your ValueSet data structure as value.

Also inside your class your JSON is this:

"values": { ... }

Your data structure is this:

[JsonProperty("values")]
public List<Value> values
{
    get;
    set;
}

Note that { .. } in JSON defines an object, where as [ .. ] defines an array. So according to your JSON you don't have a bunch of values, but you have one values object with the properties value1 and value2 of type Value.

Since the deserializer expects an array but gets an object instead, it does the least non-destructive (Exception) thing it could do: skip the value. Your property values remains with it's default value: null.

If you can: Adjust your JSON. The following would match your data structure and is most likely what you actually want:

{
    "id": "MyID",

     "values": [
         {
            "id": "100",
            "diaplayName": "MyValue1"
         }, {
            "id": "200",
            "diaplayName": "MyValue2"
         }
     ]
}

Did you check this line works perfectly & your string have value in it ?

string jsonString = sr.ReadToEnd();

if yes, try this code for last line:

ValueSet items = JsonConvert.DeserializeObject<ValueSet>(jsonString);

or if you have an array of json you can use list like this :

List<ValueSet> items = JsonConvert.DeserializeObject<List<ValueSet>>(jsonString);

good luck


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to json.net

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path Return JsonResult from web api without its properties Checking for empty or null JToken in a JObject Send JSON via POST in C# and Receive the JSON returned? Unexpected character encountered while parsing value JSON.net: how to deserialize without using the default constructor? Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' Convert Json String to C# Object List