How to Deserialize a JSON Array into an Object Using JSON.Net

Deserializing JSON Object Array with Json.net

You can create a new model to Deserialize your JSON CustomerJson:

    public class CustomerJson
{
[JsonProperty("customer")]
public Customer Customer { get; set; }
}

public class Customer
{
[JsonProperty("first_name")]
public string Firstname { get; set; }

[JsonProperty("last_name")]
public string Lastname { get; set; }

...
}

And you can deserialize your JSON easily:

JsonConvert.DeserializeObject<List<CustomerJson>>(json);

Documentation: Serializing and Deserializing JSON

How to deserialize a JSON array into an object using Json.Net?

Json.Net does not have a facility to automatically map an array into a class. To do so you need a custom JsonConverter. Here is a generic converter that should work for you. It uses a custom [JsonArrayIndex] attribute to identify which properties in the class correspond to which indexes in the array. This will allow you to easily update your model if the JSON changes. Also, you can safely omit properties from your class that you don't need, such as Filler.

Here is the code:

public class JsonArrayIndexAttribute : Attribute
{
public int Index { get; private set; }
public JsonArrayIndexAttribute(int index)
{
Index = index;
}
}

public class ArrayToObjectConverter<T> : JsonConverter where T : class, new()
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(T);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray array = JArray.Load(reader);

var propsByIndex = typeof(T).GetProperties()
.Where(p => p.CanRead && p.CanWrite && p.GetCustomAttribute<JsonArrayIndexAttribute>() != null)
.ToDictionary(p => p.GetCustomAttribute<JsonArrayIndexAttribute>().Index);

JObject obj = new JObject(array
.Select((jt, i) =>
{
PropertyInfo prop;
return propsByIndex.TryGetValue(i, out prop) ? new JProperty(prop.Name, jt) : null;
})
.Where(jp => jp != null)
);

T target = new T();
serializer.Populate(obj.CreateReader(), target);

return target;
}

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

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

To use the converter, you need to mark up your ChildModel class as shown below:

[JsonConverter(typeof(ArrayToObjectConverter<ChildModel>))]
class ChildModel
{
[JsonArrayIndex(0)]
public int ID { get; set; }
[JsonArrayIndex(1)]
public string StatusId { get; set; }
[JsonArrayIndex(2)]
public DateTime ContactDate { get; set; }
[JsonArrayIndex(3)]
public string State { get; set; }
[JsonArrayIndex(4)]
public string Status { get; set; }
[JsonArrayIndex(5)]
public string CustomerName { get; set; }
[JsonArrayIndex(6)]
public DateTime WorkStartDate { get; set; }
[JsonArrayIndex(7)]
public DateTime WorkEndDate { get; set; }
[JsonArrayIndex(8)]
public string Territory { get; set; }
[JsonArrayIndex(9)]
public string CustType { get; set; }
[JsonArrayIndex(10)]
public int JobOrder { get; set; }
[JsonArrayIndex(12)]
public string Link { get; set; }
}

Then just deserialize as usual and it should work as you wanted. Here is a demo: https://dotnetfiddle.net/n3oE3L

Note: I did not implement WriteJson, so if you serialize your model back to JSON, it will not serialize back to the array format; instead it will use the default object serialization.

Deserialize JSON as object or array with JSON.Net

You can change the property type for "data" in your model to dynamic or an object and check if it is an array on run-time.

Here's an example:

public class Response
{
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("data")]
public dynamic Data { get; set; }
}

var response = JsonConvert.DeserializeJson<Response>(json);
.
.
.

Type responseDataType = response.Data.GetType();

if(responseDataType.IsArray) {
// It's an array, what to do?
}
else {
// Not an array, what's next?
}

Deserialize JSON array of arrays into c# class

Since you have only values without properties names in your JSON, you can deserialize it into sequence of collection objects, like IEnumerable<string[]>, IEnumerable<List<string>> or List<List<string>>. Then parse every item to Person manually (assuming that you have the same structure for all items, otherwise you'll need an additional logic for checking an errors)

var result = JsonConvert.DeserializeObject<IEnumerable<string[]>>(jsonString);
var persons = result
.Select(item => new Person { Name = item[0], Age = int.Parse(item[1]), Car = item[2] })
.ToList();

Deserializing an array of objects with Json.Net

If I read your json data structure correctly you would want this:

public class Root
{
public List<Customer> rows { get; set; }
}

and

var data = JsonConvert.DeserializeObject<Root>(val);

Tested code:

void Main()
{
var test = JsonConvert.DeserializeObject<Root>("{\"rows\":[{\"id\":\"232333\",\"name\":\"nam\"},{\"id\":\"3434444\",\"name\":\"2ndName\"}]}");

Console.WriteLine(test.rows[0].id); // prints 232333
}

public class Customer
{
public int id { get; set; }
}

public class Root
{
public List<Customer> rows { get; set; }
}

Deserialize array of array using json .net

you have a double list , so or fix json or use this code

var obj = JsonSerializer.Deserialize<List<List<object>>>(json);

The class should have at least one property. Your json doesnt' have any properties at all, so only array can be used in this case. It can be converted to the class, for example like this

public class MyClass
{
public List<object> Details {get;set;}
}
var jsonParsed = JArray.Parse(json);

List<MyClass> objects = jsonParsed.Select(p => p)
.Select(x => new MyClass { Details=x.ToObject<List<object>>() }).ToList();

now if you want more details you have to convert array to your class,
Each element of array should get name, for example

public class Details
{
public Id {get; set;}
public bool IsActive {get;set}
...and so on
}

after this you can use this class already

public class MyClass
{
public Details Details {get;set;}
}

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);

Json.NET deserialize array into property

While silkfires answer didn't work for me, it gave me a hint for the solution:

I added the [JsonArray] attribute and implemented ICollection<Entry> by pointing all methods to the Entries list.

[JsonArray]
public class Collection: ICollection<Entry>
{

public LinkedList<Entry> Entries { get; } = new LinkedList<Entry>();

public void Add(Entry item)
{
Entries.AddLast(item);
}
...

Unable to deserialize a JSON array with Json.Net

There are a couple of problems here:

  1. Your JSON begins and ends with square brackets, so that means it is an array, not a single object. Since it is an array you need to use JArray.Parse() to parse it instead of JObject.Parse().
  2. Inside your array, there is a single object which contains a property areas along with a few other properties like status and code. The value of the areas property is also an array, as denoted by square brackets. So your code needs to account for both of those arrays by adding the indexes. If you want the first item, that would be index zero.
  3. There is no property called name anywhere in the JSON you posted. Instead, the names of the cities are each in a property called area.

Putting it all together, if you want to get the name New York from this JSON, you would do it like this:

Dim jResults As JArray = JArray.Parse(rawJSON)
Dim name As String = jResults(0)("areas")(0)("area")

Demo: https://dotnetfiddle.net/eAfEsx

If you're trying to get multiple names, then you would need a loop. You could do something like this:

Dim names As New List(Of String)()
For Each area As JObject In jResults(0)("areas")
Dim name As String = area("area")
names.Add(name)
Next

Demo: https://dotnetfiddle.net/BtSa6O



Related Topics



Leave a reply



Submit