JSON Parse in C# - c#

What is wrong with this code?
JSON
cities: [
{
city: {
id: 1,
name: "A.S.Peta",
status: "Active"
}
},..............
C# Code
public class Cities
{
public City[] cities;
}
public class City
{
public int id; //{ get; set; }
public string name; //{ get; set; }
public string status; //{ get; set; }
}
//De-Serialization
var jsSerialize = new JavaScriptSerializer();
var cities = jsSerialize.Deserialize<Cities>(result);
Not populating internal object City. but showing collection with all records. Any Idea?

The "inner" city in your json object is adding a nested object within the array.
Try this json code :
{
"cities": [
{
"id": 1,
"name": "A.S.Peta",
"status": "Active"
},
{
"id": 2,
"name": "Strasbourg",
"status": "Active"
}
]
}
If you need to stick to your originial json structure, you can try this c# code:
public class City2
{
public int id { get; set; }
public string name { get; set; }
public string status { get; set; }
}
public class City
{
public City2 city { get; set; }
}
public class RootObject
{
public List<City> cities { get; set; }
}
This code has been automatically generated by this very useful web tool: json2C#

Related

How to map json response to the model with different field names

I am using an ASP.NET Core 6 and System.Text.Json library.
For example, I'm getting a response from the some API with the following structure
{
"items":
[
{
"A": 1,
"User":
{
"Name": "John",
"Age": 21,
"Adress": "some str"
},
},
{
"A": 2,
"User":
{
"Name": "Alex",
"Age": 22,
"Adress": "some str2"
},
}
]
}
And I want to write this response to the model like List<SomeEntity>, where SomeEntity is
public class SomeEntity
{
public int MyA { get; set; } // map to A
public User MyUser { get; set; } // map to User
}
public class User
{
public string Name { get; set; }
public string MyAge { get; set; } // map to Age
}
How could I do it?
UPDATE:
Is it possible to map nested properties?
public class SomeEntity
{
// should I add an attribute [JsonPropertyName("User:Name")] ?
public string UserName{ get; set; } // map to User.Name
}
Use the JsonPropertyName attribute
public class Model
{
[JsonPropertyName("items")]
public SomeEntity[] Items { get; set; }
}
public class SomeEntity
{
[JsonPropertyName("A")]
public int MyA { get; set; } // map to A
[JsonPropertyName("User")]
public User MyUser { get; set; } // map to User
}
public class User
{
public string Name { get; set; }
[JsonPropertyName("Age")]
public string MyAge { get; set; } // map to Age
}
You can then deserialize it with something like
JsonSerializer.Deserialize<Model>(response);
try this please
[JsonConverter(typeof(JsonPathConverter))]
public class SomeEntity
{
[JsonProperty("items.User.Name")]
public string UserName{ get; set; } // map to User.Name
}
deserialize using :
JsonSerializer.Deserialize<SomeEntity>(response);

Pass Nested Deserialized JSON from Controller to View

After using HttpClient class to convert my JSON to a string and deserialize it with
var response = Res.Content.ReadAsStringAsync().Result;
data = JsonConvert.DeserializeObject<List<Employee>>(response);
How do I pass the data that I receive in the Controller from the call using the Model below to the View?
public class RuleType
{
public int Id { get; set; }
public string Description { get; set; }
public bool Inactive { get; set; }
}
public class RuleCategory
{
public int Id { get; set; }
public string Description { get; set; }
public bool Inactive { get; set; }
}
public class Employee
{
public string Description { get; set; }
public object EndDateTime { get; set; }
public int Id { get; set; }
public bool Inactive { get; set; }
public int RuleAction { get; set; }
public DateTime StartDateTime { get; set; }
public RuleType RuleType { get; set; }
public RuleCategory RuleCategory { get; set; }
}
Here is one object from the call
[
{
"Description": "Test Description",
"EndDateTime": null,
"Id": 1,
"Inactive": false,
"RuleAction": -2,
"StartDateTime": "2017-01-06T14:58:58Z",
"RuleType": {
"Id": 6,
"Description": "Test Description",
"Inactive": false
},
"RuleCategory": {
"Id": 1,
"Description": "Description",
"Inactive": false
}
}
]
Not sure if I'm missing something, but if you have an object you want to return to the view from the controller, you simply:
return View(viewModel); // in your case viewModel = 'data'
As others have said here already, you should be deserializing the JSON into a RootObject instead of an Employee like so:
var response = Res.Content.ReadAsStringAsync().Result;
var data = JsonConvert.DeserializeObject<List<RootObject>>(response);
You can then pass the model into the view using just:
return View(data)
You should also consider renaming RootObject into something more useful (such as employee?) as RootObject is not a very useful or descriptive name.

Retrieve the information from a nested JSON value

So I'm calling the LinkedIn API to get the profile data and it retrieves a JSON.
{
"firstName": "Cristian Viorel",
"headline": ".NET Developer",
"location": {
"country": {"code": "dk"},
"name": "Northern Region, Denmark"
},
"pictureUrls": {
"_total": 1,
"values": ["https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z..."]
}
}
I can use student.firstname, student.headline. How can I get the name of the location, or the value of the pictureUrl ?
Something like student.location.name or student.pictureUrls.values ?
Pretty easy with Json.Net. You first define your model:
public class Country
{
public string code { get; set; }
}
public class Location
{
public Country country { get; set; }
public string name { get; set; }
}
public class PictureUrls
{
public int _total { get; set; }
public List<string> values { get; set; }
}
public class JsonResult
{
public string firstName { get; set; }
public string headline { get; set; }
public Location location { get; set; }
public PictureUrls pictureUrls { get; set; }
}
Then you simply parse your Json data:
string json = #"{
'firstName': 'Cristian Viorel',
'headline': '.NET Developer',
'location': {
'country': {'code': 'dk'},
'name': 'Northern Region, Denmark'
},
'pictureUrls': {
'_total': 1,
'values': ['https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z...']
}
}";
JsonResult result = JsonConvert.DeserializeObject<JsonResult>(json);
Console.WriteLine(result.location.name);
foreach (var pictureUrl in result.pictureUrls.values)
Console.WriteLine(pictureUrl);
For the name yes, but for picture you need a for loop or if you just want the first item student.pictureUrls.values[0] (values seems to be an array).

What is the correct class structure in C# to convert this Json into?

I have the following Json below coming from a Rest service and I am trying to deserialize it into a C# object using this code:
var _deserializer = new JsonDeserializer();
var results = _deserializer.Deserialize<Report>(restResponse);
The deserialize method keeps returning null which tells me that my C# object is not structured correctly.
Below is the Json and my latest attempt at the C# definition.
{
"Report": [
{
"ID": "0000014",
"Age": "45",
"Details": [
{
"Status": "Approved",
"Name": "Joe"
},
{
"Status": "Approved",
"Name": "Bill"
},
{
"Status": "Submitted",
"Name": "Scott"
}
]
},
{
"ID": "10190476",
"Age": "40",
"Details": [
{
"Status": "Approved",
"Name": "Scott"
}
]
},
{
"ID": "10217480",
"Age": "40",
"Details": [
{
"Status": "Approved",
"Name": "Scott"
}
]
}
]
}
Here is my C# object:
public class Report
{
public List<WorkItem> Item= new List<WorkItem>();
}
public class WorkItem
{
public string ID { get; set; }
public int Age { get; set; }
public List<Details> Details { get; set; }
}
public class Details
{
public string Status { get; set; }
public string Name { get; set; }
}
Can someone advise what is wrong with my C# object definition to make this json deserialize correctly?
I would recommend using Json2Csharp.com to generate the classes.
public class Detail
{
public string Status { get; set; }
public string Name { get; set; }
}
public class Report
{
public string ID { get; set; }
public string Age { get; set; }
public List<Detail> Details { get; set; }
}
public class RootObject
{
public List<Report> Report { get; set; }
}
Try changing the Report class like so (The class name can be anything, the property must be Report)
public class WorkReport
{
public List<WorkItem> Report;
}
It should be trying to deserialize at the root into a class with an array/list of of workitem objects called Report.
You can try something like this. I have changed List to Dictionary You don't have a class defined at the root level. The class structure needs to match the entire JSON, you can't just deserialize from the middle. Whenever you have an object whose keys can change, you need to use a Dictionary. A regular class won't work for that; neither will a List.
public class RootObject
{
[JsonProperty("Report")]
public Report Reports { get; set; }
}
public class Report
{
[JsonProperty("Report")]
public Dictionary<WorkItem> Item;
}
public class WorkItem
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("Age")]
public int Age { get; set; }
[JsonProperty("Details")]
public Dictionary<Details> Details { get; set; }
}
public class Details
{
[JsonProperty("Status")]
public string Status { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
}
Then, deserialize like this:
Report results = _deserializer.Deserialize<Report>(restResponse);

Deserialize JSON with Json.NET in Windows 8 Store App (C#)

i'm trying to program a Windows Runtime Component in C# in Visual Studio 2012 for Windows 8.
I have some issues by using Json.NET to deserialize a JSON like this:
{
"header": {
"id": 0,
"code": 0,
"hits": 10
},
"body": {
"datalist": [
{
"name": "",
"city": "",
"age": 0
},
{
"name": "",
"city": "",
"age": 0
},
{
"name": "",
"city": "",
"age": 0
}
]
}
}
My intention is to get a top-level Dictionary out of this and to interpret every value as a string. For this example you would get a dictionary with two keys (header and body) and the matching values as strings. After this you could go down the tree.
A function like this
Dictionary<string, string> jsonDict =
JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
would be nice, but this one only accept string-values.
Do anybody knows how to ignore the types or get it on another way?
Furthermore to get out of the body-value "{"datalist": [ { "name": "", ....}]}" a list of dictionaries.
Thanks in advance!
I would use this site and deserialize as
var myObj =JsonConvert.DeserializeObject<RootObject>(json);
public class Header
{
public int id { get; set; }
public int code { get; set; }
public int hits { get; set; }
}
public class Datalist
{
public string name { get; set; }
public string city { get; set; }
public int age { get; set; }
}
public class Body
{
public List<Datalist> datalist { get; set; }
}
public class RootObject
{
public Header header { get; set; }
public Body body { get; set; }
}
You can also use dynamic keyword without declaring any classes
dynamic myObj =JsonConvert.DeserializeObject(json);
var age = myObj.body.datalist[1].age;
And since JObject implements IDictionary<> this is also possible
var jsonDict = JObject.Parse(json);
var age = jsonDict["body"]["datalist"][1]["age"];
If you're having a problem defining your classes, a nice feature in VS 2012 allows you to generate classes to hold your JSON/XML data using the Paste Special command under Edit. For instance, your JSON created this class:
public class Rootobject
{
public Header header { get; set; }
public Body body { get; set; }
}
public class Header
{
public int id { get; set; }
public int code { get; set; }
public int hits { get; set; }
}
public class Body
{
public Datalist[] datalist { get; set; }
}
public class Datalist
{
public string name { get; set; }
public string city { get; set; }
public int age { get; set; }
}
...which you could then deserialize your request into the type of RootObject, e.g.
var obj = JsonConvert.DeserializeObject<RootObject>(json);

Categories

Resources