Deserialize JSON string in to multiple C# objects

deserialize multiple json objects c#
deserialize json c#
json.net deserialize array of different objects
multiple json objects in one file c#
deserialize json array c#
c# json deserialize multiple types
newtonsoft json deserialize array
c# json to object

I have a JSON string in below format for which I want to deserialize it into C# List. But the record number "1","2","3" (it can be upto 1,2,3...n depends on the json response each time) in JSON restricting me to deserialize it into C# object using Newtonsoft.Json

{
"1":{
      "UID":"1",
      "LICENCENO":"licenseno",
      "NAME":"ABC"
    },
"2":{
      "UID":"2",
      "LICENCENO":"licenseno",
      "NAME":"PQR"
    },
"3":{
      "UID":"3",
      "LICENCENO":"licenseno",
      "NAME":"XYZ"      
    }
}

I am using below code for deserialization

var result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DriverMaster>>(json);

I have DriverMaster class created as-

public class DriverMaster
{
    public string UID { get; set; }
    public string LICENCENO { get; set; }
    public string NAME { get; set; }
}

Deserialization line giving unhandled exception, I know I am doing it in wrong way, because DriverMaster json object cannot be extracted into c# directly without doing something to record number 1,2,3...n in c#. Can anyone please help me to sort it out? Thanks in advance.

You were close:

var result = JsonConvert.DeserializeObject<Dictionary<string, DriverMaster>>(json)
    .Select(x => x.Value)
    .ToList();

Deserializing Json String into multiple Object types, As @YeldarKurmangaliyev already said, your json has two different objects, I think you can do something like this: var j = JArray.Parse(data);  C#. using System.Text.Json; namespace SystemTextJsonSamples { public class UpperCaseNamingPolicy : JsonNamingPolicy { public override string ConvertName(string name) => name.ToUpper (); } } Then set the JsonSerializerOptions.PropertyNamingPolicy property to an instance of your naming policy class: C#.

Solution. Change your code to use...

var result = JsonConvert.DeserializeObject<Dictionary<int, DriverMaster>>(json);

Explaination

The type is not the same... The List<DriverMaster>type will convert to JSON like so...

{
    "1":
    {
        "DriverMaster": {
            "UID":"1",
            "LICENCENO":"licenseno",
            "NAME":"ABC"
        }
    }
}

This doesn't match what you showed in your question...

The type that you are looking for is actually Dictionary<int, DriverMaster>, which is a key/value pair which will output a JSON string like so

{
    "1": { ... },
    "2": { ... },
    "3": { ... }
}

In order to fix that, you need to use the Dictionary<int, DriverMaster> type instead.

deserialize json object containing multiple objects as list, You can model the JSON differently by having a class that's a place holder for the champions dictionary: class ApiResult  If you are on the other hand deserializing the JSON given above, then deserialize using RootObject. var user = JsonConvert.DeserializeObject<RootObject>(json.ToString()).User_; with . public class RootObject { public User_ User_ { get; set; } } OR . Deserialize the following JSON instead:

You need to use

public class DriverMaster
{
    public string UID { get; set; }
    public string LICENCENO { get; set; }
    public string NAME { get; set; }
}

public class Root
{
    [JsonExtensionData]
    public IDictionary<string,JToken> Data {get;set;}
}

and

var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(json);

If you want to have result as List, you can parse the result as.

var list = new List<DriverMaster>();
foreach(KeyValuePair<string, JToken> token in result.Data)
{
    list.Add(token.Value.ToObject<DriverMaster>());
}

That would give you the desired result as

1 licenseno ABC 
2 licenseno PQR 
3 licenseno XYZ 

JSON deserialization : multiple object inside, Hide Copy Code. public class EmployeeData { public int EmpDeptId { get; set; } } public class Employee { public int ID { get; set; } public string  The reason why I do it this way is that sometimes I don't need to read all the objects. Sometimes I will need only first and second. If I just put my objects into a single json I will have to parse all the objects. I need to parse each of the objects separately to be able to decide which of them shouldn't be parsed. – PanCotzky Sep 14 '13 at

For these types of things I like to use the often overlooked feature of JToken.SelectTokens. This function allows you to select tokens within a json string and permits the use of wildcards.

Here's some code that will deserialize your sample by selecting past the 1,2,3...N in the json:

public static IEnumerable<DriverMaster> Deserialize(string json)
{
    return JToken.Parse(json).SelectTokens("*")
        .Select(jToken => jToken.ToObject<DriverMaster>());
}

The * basically says to select all tokens after the root, so it's selecting the values associated with 1, 2, 3.. etc... Here's another SO answer that shows a more complicated usage of the SelectTokens method.

Deserializing different JSON structures to the same C# class, Deserializing different JSON structures to the same C# class. June 27, 2018 an ApiError class: public class ApiError { [JsonProperty("error")] public string Error { get; set; } NET allows for a lot of flexibility in how JSON objects are deserialize. Then, in your updatePrices method you can deserialize like this: public PriceParser updatePrices() { var json = File.ReadAllText("test.json"); currentPrices = JsonConvert.DeserializeObject<Data>(json); return this; } Here is how you would dump out the data:

Serializing Collections, To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for. Json. How to convert an object to multiple JSON array respose in angular 2. convert json string to pojo class object in java. C#- deserialize json to object.

Deserialize a Collection, string json = @"['Starcraft','Halo','Legend of Zelda']"; List<string> videogames = JsonConvert.DeserializeObject<List<string>>(json); Console.WriteLine(string. Create Tree-view in JQuery using jsTree Plugin From Nested JSON Data; Deserialize n-level(multi level) JSON data to C# custom object; Read XML file in ASP.NET(C#) Creating a Graph in ASP.NET with AJAX, HttpHandler and Morris.js Plugin; Fixes For the issue "The relative virtual path 'Site.Mobile.Master' is not allowed here" of FriendlyUrls in

Migrate from Newtonsoft.Json to System.Text.Json, Deserialize inferred type to object properties, ⚠️ Not supported, workaround, sample. Deserialize JSON There's no way to allow multiple trailing commas. Json doesn't deserialize non-string values into string properties. It accepts JSON numbers and numbers within quotes while deserializing. C# Serialize and deserialize json, cannot deserialize the current JSON object Multiple json strings into one filepath Serialize and deserialize with JSON writing to “.txt” problem