How to Convert JSON Array to List of Objects in C#

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

As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into. You either need to change your JSON or change your classes. Since others have already shown how to change the JSON, I will take the opposite approach here.

To match the JSON you posted in your question, your classes should be defined like those below. Notice I've made the following changes:

  1. I added a Wrapper class corresponding to the outer object in your JSON.
  2. I changed the Values property of the ValueSet class from a List<Value> to a Dictionary<string, Value> since the values property in your JSON contains an object, not an array.
  3. I added some additional [JsonProperty] attributes to match the property names in your JSON objects.

Class definitions:

class Wrapper
{
[JsonProperty("JsonValues")]
public ValueSet ValueSet { get; set; }
}

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

class Value
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("diaplayName")]
public string DisplayName { get; set; }
}

You need to deserialize into the Wrapper class, not the ValueSet class. You can then get the ValueSet from the Wrapper.

var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

Here is a working program to demonstrate:

class Program
{
static void Main(string[] args)
{
string jsonString = @"
{
""JsonValues"": {
""id"": ""MyID"",
""values"": {
""value1"": {
""id"": ""100"",
""diaplayName"": ""MyValue1""
},
""value2"": {
""id"": ""200"",
""diaplayName"": ""MyValue2""
}
}
}
}";

var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

Console.WriteLine("id: " + valueSet.Id);
foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
{
Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);
}
}
}

And here is the output:

id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2

Convert json array into List of Objects

Based on the shown JSON array and the error message indicating that you are trying to convert an array to a single object, it looks like you were suppose to do

var RoleList = JsonConvert.DeserializeObject<List<UserAddRoleListViewModel>>(Input.RoleList);

in order to parser the JSON correctly into a List<>

How to convert Json array to list in c#

i changed & getting o/p

       public string[] allAdultFares{ get; set; }

Cannot convert JSON string to List of object

This is because you need a container class at the top that has this list of orders as a property inside of it:

public class MyData
{
public List<FoodItem> Orders { get; set; }
{

var data = JsonConvert.DeserializeObject<MyData>(strProductsInCart);
var items = data.Orders;

Also, make sure you have public properties that match the name in the JSON. They can be Pascal case, too.

Convert Json String to C# Object List

You can use json2csharp.com to Convert your json to object model

  • Go to json2csharp.com
  • Past your JSON in the Box.
  • Clik on Generate.
  • You will get C# Code for your object model
  • Deserialize by var model = JsonConvert.DeserializeObject<RootObject>(json); using NewtonJson

Here, It will generate something like this:

public class MatrixModel
{
public class Option
{
public string text { get; set; }
public string selectedMarks { get; set; }
}

public class Model
{
public List<Option> options { get; set; }
public int maxOptions { get; set; }
public int minOptions { get; set; }
public bool isAnswerRequired { get; set; }
public string selectedOption { get; set; }
public string answerText { get; set; }
public bool isRangeType { get; set; }
public string from { get; set; }
public string to { get; set; }
public string mins { get; set; }
public string secs { get; set; }
}

public class Question
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
public Model Model { get; set; }
}

public class RootObject
{
public Question Question { get; set; }
public string CheckType { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
public string ScoreIfNoMatch { get; set; }
}
}

Then you can deserialize as:

var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);

How convert JSON array or JSON object to list of object?

The easiest way to convert any JSON to .NET object is using "ToObject" method of JToken object.

public class FooConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);

if (token.Type == JTokenType.Array)
{
return token.ToObject<List<Foo>>();
}

var item = token.ToObject<Foo>();

return new List<Foo> { item };
}

public override bool CanConvert(Type objectType)
{
return true;
}

public override bool CanWrite
{
get { return false; }
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

PS. JToken object is the base class of any JSON data so we can convert JToken object to any appropriated type.

JToken             - abstract base class     
JContainer - abstract base class of JTokens that can contain other JTokens
JArray - represents an JSON array (contains an ordered list of JTokens)
JObject - represents an JSON object (contains a collection of JProperties)
JProperty - represents a JSON property (a name/JToken pair inside a JObject)
JValue - represents a primitive JSON value (string, number, boolean, null)

How to convert a JSON array into a C# List?

You need to explicitly convert the type, ie

return Json.Decode<ShoppingCart>(value);

C# Converting json array to list of objects using newtonsoft json.net

Your are getting an empty object because you did not add a [JsonProperty] attribute to the MarketOrder property in your MarketOrderList class, and the property name does not match what is in the JSON. It should be like this:

public class MarketOrderList
{
[JsonProperty(PropertyName = "array")]
public List<MarketOrder> MarketOrder { get; set; }
}

You have another issue however. The order_id values in your JSON are too large to fit in an int. You will need to change the declaration of the order_id property in your MarketOrder class to be a long to get it to work.

public class MarketOrder
{
...

[JsonProperty(PropertyName = "order_id")]
public long order_id { get; set; }

...
}

With those two changes, it will deserialize just fine.

Fiddle: https://dotnetfiddle.net/TcAfAq

Deserialize json array to c# list object

I am sure that exception is not related to you JSON string but try to remove bin and obj from solution folder and then clean and rebuild solution.

but after resolving that you will get the below exception

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'namespace.Order' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.....

Because your JSON string is List of Order so the deserialize would be change to :

List<Order> ObjOrderList = JsonConvert.DeserializeObject<List<Order>>(orderJson);

or in the other side you can also use JavaScriptSerializer like:

Order[] orderList = new JavaScriptSerializer().Deserialize<Order[]>(orderJson);

How to convert a Json string to List in c#

If you don't want to create a class :

You can use JObject.Parse() method for deserializing dynamically.



Related Topics



Leave a reply



Submit