I am trying to take this JSON:
{
"title":"string",
"description":"string",
"date":"2021-04-19T01:05:38.000Z",
"image":"url",
"images":[
"url1",
"url2"
],
"attributes":{
"phonebrand":"x",
"phonecarrier":"y",
"forsaleby":"z",
"price":12345,
"location":"daLocation",
"type":"OFFERED"
},
"url":"url to listing"
}
And convert it into this C# Object:
public class Listing {
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("date")]
public DateTime? Date { get; set; }
[JsonProperty("image")]
public string Image { get; set; }
[JsonProperty("images")]
public string[] Images { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("price")]
public decimal Price { get; set; }
[JsonProperty("locationId")]
public int LocationId { get; set; }
[JsonProperty("categoryId")]
public int CategoryId { get; set; }
[JsonProperty("sortByName")]
public string SortByName { get; set; }
[JsonProperty("q")]
public string Q { get; set; }
[JsonProperty("location")]
public string Location { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("forsaleby")]
public string ForSaleBy { get; set; }
[JsonProperty("fulfillment")]
public string Fulfillment { get; set; }
[JsonProperty("payment")]
public string Payment { get; set; }
[JsonProperty("phonebrand")]
public string? PhoneBrand { get; set; }
[JsonProperty("phonecarrier")]
public string? PhoneCarrier { get; set; }
}
My problem is, I'm trying to deserialize properties like price and phonebrand but those properties are under an object in the JSON. So when I try to deserialize them like this, those properties can't be found and are set as null. How can I deserialize those properties without changing my C# Class to include an Attributes class? I want to do this because I think that it is a cleaner/better design compared the JSON I'm taking in.
I suggest two approaches that are very explicit and easy to follow for the next developer looking at the code.
Two classes
creating a intermediate dto class that is used for deserialisation and then creating the business logic object from that intermediate object.
var withAttributes = Deserialise<ListingDto>();
var flatObject = new Listing(withAttributes);
One class
You could provide accessors at the top level which dip into the subclasses.
public class Listing
{
public AttributesDto Attributes {get; set}
...
public string Url => Attributes.Url; // Maybe '?.Url'
}
I am getting the below JSON in response from a REST API.
{
"data":{
"id":123,
"zoneid":"mydomain.com",
"parent_id":null,
"name":"jaz",
"content":"172.1 6.15.235",
"ttl":60,
"priority":null,
"type":"A",
"regions":[
"global"
],
"system_record":false,
"created_at":"2017-09-28T12:12:17Z",
"updated_at":"2017-09-28T12:12:17Z"
}
}
and trying to resolve using below code but that doesn't result in a correctly deserialized type.
var model = JsonConvert.DeserializeObject<ResponseModel>(response);
below is a class according the field I received in JSON response.
public class ResponseModel
{
public int id { get; set; }
public string zone_id { get; set; }
public int parent_id { get; set; }
public string name { get; set; }
public string content { get; set; }
public int ttl { get; set; }
public int priority { get; set; }
public string type { get; set; }
public string[] regions { get; set; }
public bool system_record { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
What is missing?
You're missing a wrapper class.
public class Wrapper
{
public ResponseModel data {get;set}
}
and then do:
var model = JsonConvert.DeserializeObject<Wrapper>(response).data;
to get the instance of your ResponseModel out the data property.
You can deduct this from your json:
{ "data":
{ "id":123, /*rest omitted */ }
}
The type that will receive this JSON needs to have a property named data. The suggested Wrapper class acts as that type.
According to json2csharp website, your model seems to be incorrect. Try this one :
public class ResponseModel
{
public int id { get; set; }
public string zoneid { get; set; }
public object parent_id { get; set; }
public string name { get; set; }
public string content { get; set; }
public int ttl { get; set; }
public object priority { get; set; }
public string type { get; set; }
public List<string> regions { get; set; }
public bool system_record { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
public class RootObject
{
public ResponseModel data { get; set; }
}
Here a cool trick you can do in Visual Studio 2015-2017 where it generates the the correct class if you just copy the JSON (ctrl + c).
You need to create a new class in visual studio and once inside the class go to Edit menu -> Paste special -> paste JSON As Classes.
Steps to generate json class
This will generate the C# object for that json for you and save you all the hassle :)
Your model does not match your response - it matches the data property. Simply wrap another object round it
public class ResponseData
{
public ResponseModel Data {get; set; {
}
and then
var model = JsonConvert.DeserializeObject<ResponseData>(response);
I am currently receiving two different types of objects in Json format and I need to deserialize those Json into corresponding objects. However, my problem is that all of those objects are sent by the same channel which means when I receive an object but I don't know which type the object is. The two different types of objects is shown below. So my question is if there is a function that allows me to try to deserialize with one object type and if that fails, I use another one?
//Object1
public class OutputStream
{
public DateTime summaryId { get; set; }
public string total { get; set; }
public int userId { get; set; }
public string dataType { get; set; }
public SensorLocation location { get; set; }
public HeartRateActivityType activityType { get; set; }
}
//Object2
public class OutputStreamAMM
{
[DataMember]
public DateTime summaryId { get; set; }
[DataMember]
public string average { get; set; }
[DataMember]
public string max { get; set; }
[DataMember]
public string min { get; set; }
[DataMember]
public int userId { get; set; }
[DataMember]
public string dataType { get; set; }
[DataMember]
public SensorLocation location { get; set; }
[DataMember]
public HeartRateActivityType activityType { get; set; }
}
Any help is appreciated.
You could write a Json Schema for one of your models, and then validate your json document against the schema to see if it matches.
You can use Newtonsoft.Json for this.
var schema = JsonSchema.Parse(...);
var jtoken = JToken.Parse(jsonString);
if(jtoken.IsValid(schema))
{
var model = jtoken.ToObject<OutputStream>();
}
else
{
var model = jtoken.ToObject<OutputStreamAMM>();
}
A simpler way would be to check for a key field that only one of the classes is known to have:
var token = JToken.Parse(jsonString);
if(token.SelectToken("$.average") != null)
{
val model = token.ToObject<OutputStreamAMM>();
}
else
{
val model = token.ToObject<OutputStream>();
}
Can you just inspect the json for some type of key identifier?
For example if the json contains "average" you have OutputStreamAMM. If not you have OutputStream.
Write a function that has that logic.
Can json.net serialize class objects into a simple dictionary?
public class CommitData
{
public AddressDTO Property { get; set; }
public DateTime? Appointment { get; set; }
public DateTime? Closed { get; set; }
public DateTime? Created { get; set; }
public string LenderRef { get; set; }
public string YearBuilt { get; set; }
public IDictionary<string, object> Custom { get; set; }
}
public class AddressDTO
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
}
When serializing I want to get:
{
"Property.Address1": "",
"Property.Address2": "uyg",
"LenderRef": "yguyg",
"Closed": date_here
}
And similarly deserialize a json string like above into the CommitData object?
Yes, but it is a bit of work. You have full control of how your object is serialized and deserialized by implementing your own JsonConverter. With that, you can flatten it and unflatten it by doing simple string manipulation. A proper generic solution could be acomplished but would take a lot more work as you would need to consider multiple levels of recursion on each property but if you only care about this case in particular then use Custom JsonConverter
Here is an example of a converter Json.net uses internally:
KeyValuePairConverter.cs
Hope it helps.
I've got an application that is receiving a JSON response. I've been trying to get it to deserialize, so I can more easily use the data in the application, but after going through several other articles on how to get this to work, I haven't had any success. The List is always empty at the end of the deserialize. The test JSON data is below, and below that is my current code.
{"vehicles":{"size":10,"next":10,"vehicle":[{"vin":"5GZCZ33Z47S000016","make":"Saturn","model":"Saturn Vue","year":2007,"manufacturer":"GM","phone":5002022424,"unitType":"EMBEDDED","primaryDriverId":450984739,"url":"https:\/\/developer.gm.com\/api\/v1\/account\/vehicles\/5GZCZ33Z47S000016","primaryDriverUrl":"https:\/\/developer.gm.com\/api\/v1\/account\/subscribers\/450984739"},{"vin":"1G6DA67VX80000014","make":"Cadillac","model":"STS AWD","year":2008,"manufacturer":"GM","phone":7039277239,"unitType":"EMBEDDED","primaryDriverId":450984752,"url":"https:\/\/developer.gm.com\/api\/v1\/account\/vehicles\/1G6DA67VX80000014","primaryDriverUrl":"https:\/\/developer.gm.com\/api\/v1\/account\/subscribers\/450984752"},{"vin":"1GNFC26069R000015","make":"Cadillac","model":"Suburban (4X2) 4 door","year":2009,"manufacturer":"GM","phone":2815079899,"unitType":"EMBEDDED","primaryDriverId":450984738,"url":"https:\/\/developer.gm.com\/api\/v1\/account\/vehicles\/1GNFC26069R000015","primaryDriverUrl":"https:\/\/developer.gm.com\/api\/v1\/account\/subscribers\/450984738"},{"vin":"1GKUKEEF9AR000010","make":"GMC","model":"Denali","year":2010,"manufacturer":"General Motors","phone":3132200010,"unitType":"EMBEDDED","primaryDriverId":548392002,"url":"https:\/\/developer.gm.com\/api\/v1\/account\/vehicles\/1GKUKEEF9AR000010","primaryDriverUrl":"https:\/\/developer.gm.com\/api\/v1\/account\/subscribers\/548392002"},{"vin":"5TFHW5F15AX000013","make":"Toyota","model":"Tundra 4WD Truck","year":2010,"manufacturer":"Toyota","phone":3372413717,"unitType":"FMV","primaryDriverId":450984766,"url":"https:\/\/developer.gm.com\/api\/v1\/account\/vehicles\/5TFHW5F15AX000013","primaryDriverUrl":"https:\/\/developer.gm.com\/api\/v1\/account\/subscribers\/450984766"},{"vin":"1G1PJ5S95B7000009","make":"Chevrolet","model":"Cruze","year":2011,"manufacturer":"General Motors","phone":8035553074,"unitType":"EMBEDDED","primaryDriverId":548392002,"url":"https:\/\/developer.gm.com\/api\/v1\/account\/vehicles\/1G1PJ5S95B7000009","primaryDriverUrl":"https:\/\/developer.gm.com\/api\/v1\/account\/subscribers\/548392002"},{"vin":"2CNALPEC3B6000001","make":"Chevrolet","model":"Equinox","year":2011,"manufacturer":"General Motors","phone":3135450001,"unitType":"EMBEDDED","primaryDriverId":450984732,"url":"https:\/\/developer.gm.com\/api\/v1\/account\/vehicles\/2CNALPEC3B6000001","primaryDriverUrl":"https:\/\/developer.gm.com\/api\/v1\/account\/subscribers\/450984732"},{"vin":"1GCRCSE09BZ000005","make":"Chevrolet","model":"Silverado Crew Cab","year":2011,"manufacturer":"General Motors","phone":8035553074,"unitType":"EMBEDDED","primaryDriverId":450984732,"url":"https:\/\/developer.gm.com\/api\/v1\/account\/vehicles\/1GCRCSE09BZ000005","primaryDriverUrl":"https:\/\/developer.gm.com\/api\/v1\/account\/subscribers\/450984732"},{"vin":"1G1RD6E47BU000008","make":"Chevrolet","model":"Volt","year":2011,"manufacturer":"General Motors","phone":3139030008,"unitType":"EMBEDDED","primaryDriverId":548392002,"url":"https:\/\/developer.gm.com\/api\/v1\/account\/vehicles\/1G1RD6E47BU000008","primaryDriverUrl":"https:\/\/developer.gm.com\/api\/v1\/account\/subscribers\/548392002"},{"vin":"1G6DH5E53C0000003","make":"Cadillac","model":"CTS Coupe","year":2012,"manufacturer":"General Motors","phone":3136440003,"unitType":"EMBEDDED","primaryDriverId":450438292,"url":"https:\/\/developer.gm.com\/api\/v1\/account\/vehicles\/1G6DH5E53C0000003","primaryDriverUrl":"https:\/\/developer.gm.com\/api\/v1\/account\/subscribers\/450438292"}]}}
This is the function from the Main Form that is handling passing the info into objects.
void Deserialize(IRestResponse response)
{
string workingString = response.Content;
var list = new JavaScriptSerializer().Deserialize<List<GMVehicles>>(workingString);
}
These are the classes that the deserialzer should be putting the data
public class GMVehicles
{
public Vehicle vehicle { get; set; }
}
public class Vehicle
{
public string vin { get; set; }
public string make { get; set; }
public string model { get; set; }
public string year { get; set; }
public string manufacturer { get; set; }
public string phone { get; set; }
public string unitType { get; set; }
public string primaryDriverId { get; set; }
public string url { get; set; }
public string primaryDriverUrl { get; set; }
}
What am I doing wrong?
Your Vehicle class is fine. Now you need a wrapper around your GMVehicles class:
public class Root
{
public GMVehicles Vehicles { get; set; }
}
also your GMVehicles is wrong, it should contain a collection (because the vehicle property in your JSON is a list, not an object):
public class GMVehicles
{
public Vehicle[] Vehicle { get; set; }
}
Alright, now you deserialize the root:
void Deserialize(IRestResponse response)
{
string workingString = response.Content;
var root = new JavaScriptSerializer().Deserialize<Root>(workingString);
Vehicle[] list = root.Vehicles.Vehicle;
// ... do something with the list of vehicles here
}