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);
Deserialize JSON array(or list) in C#
This code works for me:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
namespace Json
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(DeserializeNames());
Console.ReadLine();
}
public static string DeserializeNames()
{
var jsonData = "{\"name\":[{\"last\":\"Smith\"},{\"last\":\"Doe\"}]}";
JavaScriptSerializer ser = new JavaScriptSerializer();
nameList myNames = ser.Deserialize<nameList>(jsonData);
return ser.Serialize(myNames);
}
//Class descriptions
public class name
{
public string last { get; set; }
}
public class nameList
{
public List<name> name { get; set; }
}
}
}
Deserialize json array of array to List of string in C#
You have not only string in your collection and you have nested arrays, so List<string>
does not represent your JSON structure. If you want to get only string you can do something like this (this one is with Newtonsoft, after fixing the d
value):
var strings = JsonConvert.DeserializeObject<List<List<object>>>(json)
.Select(arr => arr.OfType<string>().ToList())
.ToList();
Or using arr => arr.Select(a => a?.ToString()
in Select
if you want to convert all values to strings.
Or you can convert to List<JArray>
with Newtonsoft and call ToString
on it:
List<string> strings = JsonConvert.DeserializeObject<List<JArray>>(json)
.Select(jarr => jarr.ToString(Newtonsoft.Json.Formatting.None))
.ToList();
Console.WriteLine(string.Join(", ", strings)); // prints "["a","b","c",null,1], ["d","e",null,2]"
C# JSON Deserialization: How to get values out of a JSON array of objects
{
"project": [
{
"id": 1,
"keyName": "John123",
"age": "19",
"token": "123456789"
},
{
"id": 2,
"keyName": "Mary123",
"age": "13",
"token": "23435"
},
{
"id": 3,
"keyName": "Harry123",
"age": "23",
"token": "2343542"
}
]
}
You can use Newtonsoft.Json
framework for json manipulation, which you can install from NuGet Package Manager
. Then do a Project
model with the data that you need. You can abstract it even further with JSONData
class, so if your json data grows you can just add new properties to it. After that just deserialize it.
public class Project
{
public string KeyName { get; set; }
public string Token { get; set; }
}
public class JSONData
{
public List<Project> Projects { get; set; }
}
public class Deserializer
{
//---------------- FIELDS -----------------
private readonly string path = @"../../yourJsonFile.json";
private readonly JSONData jsonData;
//------------- CONSTRUCTORS --------------
public Deserializer() {
this.jsonData = JsonConvert.DeserializeObject<JSONData>(File.ReadAllText(this.path));
}
}
That way you won't duplicate deserialization code like this
JsonConvert.DeserializeObject<List<Project>>(path);
JsonConvert.DeserializeObject<List<Category>>(path);
JsonConvert.DeserializeObject<List<Product>>(path);
Deserialize json to List<object> in C#
There is an error in your json - it's missing a closing ]
for the array (I'll assume it's a typo).
The real problem is that you need a wrapper class to represent the data
node of the json which should contain a list (or array) of ExPositions
. The makerPositions
and takerPositions
should also become lists (or arrays) too. Add the following class and update the position properties of ExPositions
:
public class Data
{
public List<ExPositions> data { get; set; }
}
// change positions to use a List too
public class ExPositions
{
...
public List<Positions> makerPositions { get; set; }
public List<Positions> takerPositions { get; set; }
}
Then you can deserialize using:
var result = JsonSerializer.Deserialize<Data>(json);
It's not clear where the ""total"": 2
property should be in your models (it's not clear in the json because of the issue I mentioned), you could add it to the Data
class above (if it belongs there).
Online demo
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 JSON Object into C# list
You are trying to deserialize into a List
List<NewDocumentObject> newDoc = JsonConvert.DeserializeObject<List<NewDocumentObject>>(response.Content.ReadAsStringAsync().Result);
But your JSON string contains an object {}
only.
Change your JSON input to [{...}]
Or change your deserialize call to only one object.
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.
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'portal.Models.SubProjectViewRecord'
Apparently looks like from the error that there are multiple items in the array that is why there is any array returned from the api reponse. you can use a List<T>
for it and the code for it would be like :
List<Models.SubProjectViewRecord> oop = JsonConvert.DeserializeObject<List<Models.SubProjectViewRecord>>(objJson);
While your model would be below assuming that the json array elements are of json object with Id
and Name
members in it:
public class SubProjectViewRecord
{
public string Name { get; set; }
public int Id { get; set; }
}
Related Topics
How to Check Byte Array Empty or Not
How to Get the Xml Soap Request of an Wcf Web Service Request
Add Spaces Before Capital Letters
How to Redirect to Login Page If Session Is Not Available in MVC
How to Convert a Dictionary to a Json String in C#
Split a Comma-Separated String With Both Quoted and Unquoted Strings
How to Cast Object to List<Object> and Turn It into an Array
C# - How to Save Byte Values to File With Smallest Size Possible
How to Automatically Increment Numbers in C#
How to Check If an Object Has Changed
How to Write Data on Multiple Lines But Within the Same Cell of Csv
Automatically Update Values in Database from Datagridview
How to Get the Am/Pm Value from a Datetime
Generate Xml for <Govtalkmessage Xmlns="Http://Www.Govtalk.Gov.Uk/Cm/Envelope">
Use Linq to Collaps Multiply Collections into One Collection
How to Get the List of Properties of a Class
Reading Only Specific Columns from a CSV File Out of Many
Repaired Records:Cell Information from Worksheet Created from Scratch