I have json file, how can I deserialize this? As I understood json file had array which has 3 elements, but I didn't understand what is inside elements Id, Name, Driver and data inside Driver what is this (Driver) object?
[
{
"Id":1,
"Name":"Renault Magnum",
"Driver":{
"Name":"John",
"Surname":"Dou",
"Age":35,
"Experience":10
},
"State":"base"
},
{
"Id":2,
"Name":"Volvo FH12",
"Driver":{
"Name":"Jack",
"Surname":"Dou",
"Age":55,
"Experience":30
},
"State":"base"
},
{
"Id":3,
"Name":"DAF XF",
"Driver":{
"Name":"Jane",
"Surname":"Dou",
"Age":45,
"Experience":15
},
"State":"base"
}
]
You can use the Paste Special-Feature of Visual Studio to generate classes from a json. By applying this technique to the json above, you get the following classes as a result:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public int Id { get; set; }
public string Name { get; set; }
public Driver Driver { get; set; }
public string State { get; set; }
}
public class Driver
{
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public int Experience { get; set; }
}
This indicates that the answer to your question what is inside elements Id, Name, Drivder and data inside Driver what is this (Driver) object? is: Yes, it is an object.
I would recommend naming the elements in a useful way though ;-)
Related
I'm trying to deserialize JSON without declaring every property in C#. Here is a cut-down extract of the JSON:
{
"resourceType": "export",
"type": "search",
"total": 50,
"timestamp": "2020-08-02T18:26:06.747+00:00",
"entry": [
{
"url": "test.com/123",
"resource": {
"resourceType": "Slot",
"id": [
"123"
],
"schedule": {
"reference": {
"value": "testvalue"
}
},
"status": "free",
"start": "2020-08-03T08:30+01:00",
"end": "2020-08-03T09:00+01:00"
}
}
]
}
I want to get the values out of entry → resource, id and start.
Any suggestions on the best way to do this?
I've made very good experiences with json2sharp. You can enter your JSON data there and it will generate the classes you need to deserialize the JSON data for you.
public class Reference
{
public string value { get; set; }
}
public class Schedule
{
public Reference reference { get; set; }
}
public class Resource
{
public string resourceType { get; set; }
public List<string> id { get; set; }
public Schedule schedule { get; set; }
public string status { get; set; }
public string start { get; set; }
public string end { get; set; }
}
public class Entry
{
public string url { get; set; }
public Resource resource { get; set; }
}
public class Root
{
public string resourceType { get; set; }
public string type { get; set; }
public int total { get; set; }
public DateTime timestamp { get; set; }
public List<Entry> entry { get; set; }
}
The next step is to choose a framework which will help you to deserialize. Something like Newtonsoft JSON.
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
If you want to get the data without declaring classes, you can use Json.Net's LINQ-to-JSON API (JToken, JObject, etc.). You can use the SelectToken method with a JsonPath expression to get what you are looking for in a couple of lines. Note that .. is the recursive descent operator.
JObject obj = JObject.Parse(json);
List<string> ids = obj.SelectToken("..resource.id").ToObject<List<string>>();
DateTimeOffset start = obj.SelectToken("..resource.start").ToObject<DateTimeOffset>();
Working demo here: https://dotnetfiddle.net/jhBzl4
If it turns out there are actually multiple entries and you want to get the id and start values for all of them, you can use a query like this:
JObject obj = JObject.Parse(json);
var items = obj["entry"]
.Children<JObject>()
.Select(o => new
{
ids = o.SelectToken("resource.id").ToObject<List<string>>(),
start = o.SelectToken("resource.start").ToObject<DateTimeOffset>()
})
.ToList();
Demo: https://dotnetfiddle.net/Qe8NB7
I am not sure why you don't deserialize the lot (even if it's minimally populated) since you have to do the inner classes anyway.
Here is how you could bypass some of the classes (1) by digging into the JObjects
Given
public class Reference
{
public string value { get; set; }
}
public class Schedule
{
public Reference reference { get; set; }
}
public class Resource
{
public string resourceType { get; set; }
public List<string> id { get; set; }
public Schedule schedule { get; set; }
public string status { get; set; }
public string start { get; set; }
public string end { get; set; }
}
public class Entry
{
public string url { get; set; }
public Resource resource { get; set; }
}
You could call
var results = JObject.Parse(input)["entry"]
.Select(x => x.ToObject<Entry>());
I have JSON returning in the following format:
{
"Items": [
{
"unique_id": "11111111111",
"rages": {
"rage_content": "Hello rage 2",
"date_stamp": "21/07/2017",
"id": 2
}
},
{
"unique_id": "2222222222",
"rages": {
"rage_content": "Hello rage 1",
"date_stamp": "21/07/2017",
"id": 1
}
}
],
"Count": 2,
"ScannedCount": 2
}
And I have the following 2 classes defined:
Items.cs:
namespace ragevent_A0._0._1
{
class Items
{
public String rage_id { get; set; }
public rage rage { get; set; }
}
}
rage.cs:
class rage
{
public String rage_content { get; set; }
public String date_stamp { get; set; }
public int id { get; set; }
}
I am using the following code in order to attempt to deseralize the JSON returned above:
List<Items> data = JsonConvert.DeserializeObject<List<Items>>(json);
However, I am not able to successfully deserialize the data due to the above error. I have tried a few solutions online, however I have not managed to find a solution which works with the format of my returned JSON. I have used a JSON formatter and it is formatted correctly, so that shouldn't be the issue.
Any help would be much appreciated!
For the posted JSON data below should be the model you need (credit: http://json2csharp.com/). There is mismatch between the property name rage_id. You can use JsonProperty attribute
public class Rages
{
public string rage_content { get; set; }
public string date_stamp { get; set; }
public int id { get; set; }
}
public class Item
{
[JsonProperty(Name="rage_id")]
public string unique_id { get; set; }
public Rages rages { get; set; }
}
public class RootObject
{
public List<Item> Items { get; set; }
public int Count { get; set; }
public int ScannedCount { get; set; }
}
Your deserialization should be
var data = JsonConvert.DeserializeObject<RootObject>(json);
I just can't find a proper solution for this problem though i came across the same topic which was asked before.
Here is my sample Json which i am posting to a web api controller
{
"AppointmentId ":2079,
"manageaptarray":[
"VanId":6,
"Doctors":[
{"Id":1,"Name":Doc1},
{"Id":2,"Name":Doc2}
]
]}
Here is my c# class
public class ManageDoctorModel
{
public int Id { get; set; }
public int AppointmentId { get; set; }
public DateTime? AppointmentAt { get; set; }
public DateTime ScheduledAt { get; set; }
public int? ModifiedBy { get; set; }
public DateTime? ModifiedDateTime { get; set; }
public Nullable<bool> rCreate { get; set; }
public Nullable<bool> rUpdate { get; set; }
public Nullable<bool> rDelete { get; set; }
public Nullable<bool> rView { get; set; }
public jsonarray[] manageaptarray { get; set; }
}
public class jsonarray
{
public int VanId { get; set; }
public string VanName { get; set; }
public List<Doctorslist> Doctors { get; set; }
}
}
when i do so i get the error "cannot deserialize the current json array (e.g. 1 2 3 ) into type...."
I searched around stack & other forums most of the suggestion was to deserialize the json array.So here is what i did in my c# code
List<jsonarray> jsondata = JsonConvert.DeserializeObject<System.Collections.Generic.List<jsonarray>>(value.manageaptarray.ToString());
Note : value is the param where i get this json.
I tried some changes in my class files like doing idictionary<string,object> but that gives me the same error.
Since i am working with angularjs i tried the following
json.stringify(jsondata)
angular.tojson(jsondata)
json.parse(jsondata)
but no luck with that.Please help me out here.To what i have understood i think passing array within an array is the problem that is causing the trouble.So if anyone can help me how to figure this out it would be greatful so that i wont be wasting more time on this.
Thanks in advance and wish you all a very happy new year 2016 <3
Kind Note to mods : I know this is a repeative question but most of the questions aren't dealt with array of array in json.
The JSON that you show in your question, in not a valid JSON:
{
"AppointmentId ":2079,
"manageaptarray": [
"VanId": 6,
"Doctors": [
{
"Id":1,
"Name": Doc1
},
{
"Id":2,
"Name":Doc2
}
]
]
}
The manageaptarray is a invalid array syntax, also in JSON syntax, Doc1 and Doc2 isn't a valid value, probably they are a string, so they should be between double quotes.
You must fix the JSON first, then you can look my answer Deserialize JSON into Object C#, that show how to convert a valid JSON in a C# class using Visual Studio 2013/15.
A valid JSON should be like that:
{
"AppointmentId ":2079,
"manageaptarray": [
{
"VanId": 6,
"Doctors": [
{
"Id":1,
"Name": "Doc1"
},
{
"Id":2,
"Name": "Doc2"
}
]
}
]
}
And the C# class that match this, is:
public class Rootobject
{
public int AppointmentId { get; set; }
public Manageaptarray[] manageaptarray { get; set; }
}
public class Manageaptarray
{
public int VanId { get; set; }
public Doctor[] Doctors { get; set; }
}
public class Doctor
{
public int Id { get; set; }
public string Name { get; set; }
}
Then you can Deserialize this JSON into a class now using:
Rootobject jsondata = JsonConvert.DeserializeObject<Rootobject>(jsonString);
Could someone help me in structuring the class for below format JSON.
I have already tried http://json2csharp.com/ tool. It did not work as my list of people are dynamic, i.e. values 123, 124 etc are not pre-defined.
{
"people":
{
"123":"jack henry",
"124":"john henry",
"125":"jill henry",
"215":"jim henry",
...
}
}
public class Root
{
public Dictionary<string, string> people = new Dictionary<string,string>();
}
Using Json.NET:
Root root = new Root();
root.people.Add("123", "jack henry");
//... Add more people
string json = JsonConvert.SerializeObject(root);
Visual Studio > Edit > Paste Special > Paste JSON as classes
public class Rootobject
{
public People people { get; set; }
}
public class People
{
public string _123 { get; set; }
public string _124 { get; set; }
public string _125 { get; set; }
public string _215 { get; set; }
}
You already got an answer for your question. But, looking at the sample JSON looks like you are actually storing a list of persons. If that is the case, you might create classes like this
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class People
{
public List<Person> Persons { get; set; }
//other properties
}
And have your JSON standardized as
{
"Persons": [
{
"Id": 123,
"Name": "Jack"
},
{
"Id": 124,
"Name": "John"
}
]
}
Which will be much more meaningful and readable (by code and human).
Source: http://json2csharp.com/
public class People
{
public string __invalid_name__123 { get; set; }
public string __invalid_name__124 { get; set; }
public string __invalid_name__125 { get; set; }
public string __invalid_name__215 { get; set; }
}
public class RootObject
{
public People people { get; set; }
}
I'm creating a Steam APP ( For the Steam Platform ), and i need to deserialize a JSON file.
{
"response": {
"success": 1,
"current_time": 1401302092,
"raw_usd_value": 0.245,
"usd_currency": "metal",
"usd_currency_index": 5002,
"items": {
"A Brush with Death": {
"defindex": [
30186
],
"prices": {
"6": {
"Tradable": {
"Craftable": [
{
"currency": "metal",
"value": 4,
"last_update": 1398990171,
"difference": 0.17
}
]
}
}
}
},
...
I just need to get Defindex and value. Already deserialized some simple JSON files, but i think this one is more complex.
For those who wants to know, I am using the API from BackpackTF...
Use NewtonSoft.Json And then you can use it as follows to get the data out.
dynamic json = JsonConvert.DeserializeObject(<yourstring>);
string currency = json.response.usd_currency; // "metal"
In general, what you want to do is making sure you have valid JSON (use JSON LINT for that), then get a C# class definition with Json2CSharp, then you will do something like this:
MyClass myobject=JsonConvert.DeserializeObject<MyClass>(json);
(We're assuming MyClass is based on what you got from Json2CSharp)
Then you access the values you want via the traditional C# dot notation.
Use a nuget package caller Newtonsoft.Json.5.0.8. it is on the nuget repository.
This line of code will take your json as a string, and turn it into its root object.
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonString);
The Json you provided is slightly flawed, but im guessing that the structure of c# objects you would be looking for would be close to this:
public class Craftable
{
public string currency { get; set; }
public int value { get; set; }
public int last_update { get; set; }
public double difference { get; set; }
}
public class Tradable
{
public List<Craftable> Craftable { get; set; }
}
public class Prices
{
public Tradable Tradable{ get; set; }
}
public class Items
{
public List<int> defindex { get; set; }
public Prices prices { get; set; }
}
public class Response
{
public int success { get; set; }
public int current_time { get; set; }
public double raw_usd_value { get; set; }
public string usd_currency { get; set; }
public int usd_currency_index { get; set; }
public Items items { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}