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;
}
Answer from I4V on Stack OverflowThis 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;
}
This code is working fine for me,
var a = serializer.Deserialize<List<Entity>>(json);
Deserializing a JSON array string into a C# object
C# deserialize JSON array - Unity Engine - Unity Discussions
JSON Array deserialization
How to Deserialize JSON array(or list) in C# - Stack Overflow
Videos
If your array continues with X4,Y4,Z4, you have a problem since, for deserializing the strong type class from the JSON, the array entries should be known. To deserialize the current JSON, use the following classes:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string X1 { get; set; }
public string Y1 { get; set; }
public string Z1 { get; set; }
public string X2 { get; set; }
public string Y2 { get; set; }
public string Z2 { get; set; }
public string X3 { get; set; }
public string Y3 { get; set; }
public string Z3 { get; set; }
}
You may read the JSON dynamically instead of deserializing the array:
using System.Text.Json.Nodes;
var jsonString = "[{\"X1\":\"x1\",\"Y1\":\"y1\",\"Z1\":\"z1\"},{\"X2\":\"x2\",\"Y2\":\"y2\",\"Z2\":\"z2\"},{\"X3\":\"x3\",\"Y3\":\"y3\",\"Z3\":\"z3\"}]";
var jsonObject = JsonNode.Parse(jsonString);
Console.WriteLine(jsonObject.ToString());
Console.WriteLine(jsonObject[0]["X1"]);
Alon.
Hi @Julio Bello ,
[{"X1":"x1","Y1":"y1","Z1":"z1"},{"X2":"x2","Y2":"y2","Z2":"z2"},{"X3":"x3","Y3":"y3","Z3":"z3"},...]
From the above JSON string, we can see that each property (key-value pair, such as "X1":"x1", "X2":"x2") has a different property name or key value, in this scenario the property is not fixed so we can directly use it as the class's property.
So, for the above JSON string, I suggest you could deserialize it uses a Dictionary, you can refer to the following sample code:
//required using System.Text.Json;
var values = new List>()
{
new Dictionary()
{
{"X1", "x1"},{"Y1", "Y1"},{"Z1", "Z1"}
},
new Dictionary()
{
{"X2", "x2"},{"Y2", "Y2"},{"Z2", "Z2"}
}
};
var jsonstring = JsonSerializer.Serialize(values);
//jsonstring: [{"X1":"x1","Y1":"Y1","Z1":"Z1"},{"X2":"x2","Y2":"Y2","Z2":"Z2"}]
var reult1 = JsonSerializer.Deserialize>>(jsonstring);
var test = new TestModel()
{
Item = new List>()
{
new Dictionary()
{
{"X1", "x1"},{"Y1", "Y1"},{"Z1", "Z1"}
},
new Dictionary()
{
{"X2", "x2"},{"Y2", "Y2"},{"Z2", "Z2"}
}
}
};
var jsonstring2 = JsonSerializer.Serialize(test);
//josnstring2: {"Item":[{"X1":"x1","Y1":"Y1","Z1":"Z1"},{"X2":"x2","Y2":"Y2","Z2":"Z2"}]}
var result2 = JsonSerializer.Deserialize(jsonstring2);
The TestModel
public class TestModel
{
public List> Item { get; set; }
}
The output is like this:
And this sample code:
var jsonstr = "[{\"X1\":\"x1\",\"Y1\":\"Y1\",\"Z1\":\"Z1\"},{\"X2\":\"x2\",\"Y2\":\"Y2\",\"Z2\":\"Z2\"}]";
var result3 = JsonSerializer.Deserialize>>(jsonstr);
The result:
After that you can find the data from the Dictionary. More detailed information about Dictionary, see Dictionary Class
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion
When api returns a bad request, in the response content it returns a json array with a single string inside it. E.g. “[\“Movie not allowed in this region\”]” how to deserealize this with C# to get the string only?
Right now I deserialize using Newtonsofts deserealizeObject<List<string>> then I call the first method on that list to get the string. Is there a cleaner way of handling this scenario?
Hi, I have what I think is just a case of bad API design that I have to deal with.
So What I get returned from the api, is a json object with x fields in them, being names of providers of articles. It looks like this:
{
"status": "ok",
"result": {
"firstprovider": [ .... ],
"secondprovider": [ ...],
"thirdprovider": [ ... ]
}
}In this example, only three provider are returned, but I could get more or less than that, and their names may vary. It's quite important that I save those names.
Each of the providers are objects, which are always formed in the same manner.
But, I would like to store the provider objects in a list of providers List<Provider>, where the name of the provider is included as a field in the Provider object.
How would one do that? It seems to me that "result" should actually have been an array for me to do this properly, but is there any way that I can get around this, and do what I am descirbing?
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
For those who don't want to create any models, use the following code:
var result = JsonConvert.DeserializeObject<
List<Dictionary<string,
Dictionary<string, string>>>>(content);
Note: This may not work for your JSON string. This is not a general solution for any JSON structure. It works for the JSON structure in the question. For your own JSON structure, you need to adjust the code.
You need to create a structure like this:
public class Friends
{
public List<FacebookFriend> data {get; set;}
}
public class FacebookFriend
{
public string id {get; set;}
public string name {get; set;}
}
Then you should be able to do:
Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(result);
The names of my classes are just an example. You should use proper names.
Adding a sample test:
string json =
@"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}";
Friends facebookFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Friends>(json);
foreach(var item in facebookFriends.data)
{
Console.WriteLine("id: {0}, name: {1}", item.id, item.name);
}
Produces:
id: 518523721, name: ftyft
id: 527032438, name: ftyftyf
id: 527572047, name: ftgft
id: 531141884, name: ftftft
Sometimes I prefer dynamic objects:
public JsonResult GetJson()
{
string res;
WebClient client = new WebClient();
// Download string
string value = client.DownloadString("https://api.instagram.com/v1/users/000000000/media/recent/?client_id=clientId");
// Write values
res = value;
dynamic dyn = JsonConvert.DeserializeObject(res);
var lstInstagramObjects = new List<InstagramModel>();
foreach(var obj in dyn.data)
{
lstInstagramObjects.Add(new InstagramModel()
{
Link = (obj.link != null) ? obj.link.ToString() : "",
VideoUrl = (obj.videos != null) ? obj.videos.standard_resolution.url.ToString() : "",
CommentsCount = int.Parse(obj.comments.count.ToString()),
LikesCount = int.Parse(obj.likes.count.ToString()),
CreatedTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds((double.Parse(obj.created_time.ToString()))),
ImageUrl = (obj.images != null) ? obj.images.standard_resolution.url.ToString() : "",
User = new InstagramModel.UserAccount()
{
username = obj.user.username,
website = obj.user.website,
profile_picture = obj.user.profile_picture,
full_name = obj.user.full_name,
bio = obj.user.bio,
id = obj.user.id
}
});
}
return Json(lstInstagramObjects, JsonRequestBehavior.AllowGet);
}