Deserialize a JSON Array in C#

Deserialize a JSON array in C#

This should work...

JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);

public class Person
{
public string Name;
public int Age;
public string Location;
}
public class Record
{
public Person record;
}

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

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 object to array

You can create a new class:

public class MyClass {

[JsonProperty("name")]
public string Name { get; set; }

[JsonProperty("dir")]
public string Dir { get; set; }

[JsonProperty("valid")]
public bool Valid { get; set; }
}

And then just use deserialize:

var data = JsonConvert.DeserializeObject<MyClass[]>(myJsonResponse).Select(x => x.Name).ToArray();

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]"

Deserialize JSON with an array into DataTable?

You got an deserialize error "... Expected StartArray, got StartObject." So you can not to deserialize to DataTable the whole object , you need an array part only. An array part starts from "artists". So after parsing the whole object you have to deserilize "artists" part only.

try this. it was tested in Visual Studio

var jsonObject=JObject.Parse(json);
DataTable dt = jsonObject["artists"].ToObject<DataTable>();

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.

How do I deserialize a JSON array using Newtonsoft.Json

Try this code:

public class Receiver 
{
public string receiver_tax_id { get; set;}
public string total { get; set;}
public string receiver_company_name { get; set;}
public int status { get; set;}
}

And deserialize looks like follows:

var result = JsonConvert.DeserializeObject<List<Receiver>>(responseString);
var status = result[0].status;

C# Can't get this json deserialized

try

foto = JsonConvert.DeserializeObject<List<Model.Fotos>>(parte_fotos);


Related Topics



Leave a reply



Submit