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);
Related
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.
I'm using Newtonsoft to deserialize JSON data to an object.
My JSON looks like this:
{
"id": "4aa50d01-41bd-45e3-803e-f479a948acf1",
"referenceNumber": "120064",
"status": "Application in Progress",
"borrowers": [
{
"name": "John Doe",
"type": "BORROWER"
},
{
"name": "Jane Doe",
"type": "COBORROWER"
}
],
"propertyAddress": {
"zipCodePlusFour": ""
}
}
The borrowers array can have up to 2 items. 1 with type == "BORROWER"and the other with type == "COBORROWER"
I have a LoanItem class I am deserializing to.
public class LoanItem
{
public string referenceNumber { get; set; }
public string status { get; set; }
}
I know I can mark the LoanItem property with the JSONProperty attribute but I'm wondering if there is a way I can add an array sub item with a condition.
Something maybe like
[JSONProperty("borrowers[WHERE type = 'BORROWER'].name")]
public string BorrowerName { get; set; }
[JSONProperty("borrowers[WHERE type = 'COBORROWER'].name")]
public string CoBorrowerName { get; set; }
Is this possible? Can I use the JSONProperty attribute?
Create a new class Borrower
public class Borrower
{
string Name { get; set; }
string Type { get; set; }
}
Update your LoanItem class to this
public class LoanItem
{
public string referenceNumber { get; set; }
public string status { get; set; }
public List<Borrower> Borrowers {get;set;}
public string BorrowerName { get { return Borrowers.Where(x=>x.Type == "BORROWER").FirstOrDefault().Name; }
public string CoBorrowerName { get { return return Borrowers.Where(x=>x.Type == "COBORROWER").FirstOrDefault().Name; } }
}
Now you can access the BorrowerName and CoborrowerName
I have the following json:
{
"cuisines": [
{
"cuisine": {
"cuisine_id": 152,
"cuisine_name": "African"
}
},
{
"cuisine": {
"cuisine_id": 1,
"cuisine_name": "American"
}
},
{
"cuisine": {
"cuisine_id": 4,
"cuisine_name": "Arabian"
}
},
{
"cuisine": {
"cuisine_id": 151,
"cuisine_name": "Argentine"
}
}
]
}
Im using RestSharp to get the data and sending it to JSON.Net:
JsonConvert.DeserializeObject<Cuisines>(content)
And I'm using the following classes:
public class Cuisine
{
[JsonProperty("cuisine_id")]
public string cuisine_id { get; set; }
[JsonProperty("cuisine_name")]
public string cuisine_name { get; set; }
}
public class Cuisines
{
[JsonProperty("cuisines")]
public List<Cuisine> AllCuisines { get; set; }
}
What is wierd is, the return data is finding 81 cuisine objects on my request, but all the Cuisine info is null.
You model needs one more class. So it should be
public class Cuisine
{
[JsonProperty("cuisine_id")]
public string cuisine_id { get; set; }
[JsonProperty("cuisine_name")]
public string cuisine_name { get; set; }
}
public class CuisineWrapper
{
public Cuisine cuisine { get; set; }
}
public class Cuisines
{
[JsonProperty("cuisines")]
public List<CuisineWrapper> AllCuisines { get; set; }
}
Your classes definitions doesn't match provided JSON. Top level array contains objects with a single property (object) cuisine, like so:
"cuisine": {
"cuisine_id": 152,
"cuisine_name": "African"
}
where as your C# List<Cuisine> contains objects directly exposing cuisine_id and cuisine_name. If you can't change JSON, decorate class Cuisine with JsonObjectAttribute
You actually have 3 objects - A root object that contains a property named cuisines that is a collection of Cuisine.
When you paste your JSON as classes in visual studio you get the following structure (which you would probably want to rename some things and list-ify the array)
public class Rootobject
{
public Cuisine[] cuisines { get; set; }
}
public class Cuisine
{
public Cuisine1 cuisine { get; set; }
}
public class Cuisine1
{
public int cuisine_id { get; set; }
public string cuisine_name { get; set; }
}
Your JSON is nested more than your class structure. If you can change your JSON to the form:
"cuisines": [
{
"cuisine_id": 152,
"cuisine_name": "African"
},
{
"cuisine_id": 1,
"cuisine_name": "American"
},
.. etc
Then it will match your class structure.
Alternatively, change your class structure to match the JSON:
public class Cuisine
{
[JsonProperty("cuisine")]
public CuisineData data { get; set; }
}
public class CuisineData
{
[JsonProperty("cuisine_id")]
public string cuisine_id { get; set; }
[JsonProperty("cuisine_name")]
public string cuisine_name { get; set; }
}
public class Cuisines
{
[JsonProperty("cuisines")]
public List<Cuisine> AllCuisines { get; set; }
}
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);
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#