Json Desearialization C# URL - c#

I have this problem:
I'm consuming a JSON from backend which contains this:
"results": [{
"id": "3bc895f3-2439-4db8-8015-ddf82841c26b",
"code": "test",
"urlImagePromotion": "http://mmblob.blob.core.windows.net/img/img_02a479e2_4b41_4c34_bb34_afda77dbad9e.png"
}]
When i deserialize to my class, the attribute urlImagePromotion is allways null.
var response = JsonConvert.DeserializeObject<MultiResultResponse<TestClass>>(result);
public class MultiResultResponse<T>
{
public IEnumerable<T> Results { get; set; }
}
My TestClass:
public Guid? Id { get; set; }
public string Code { get; set; }
[JsonProperty("urlImagePromotion")]
public string UrlImagePromotion { get; set; }
Maybe its allways null because that string has special characters?
How can i get the correct value?
Thanks you

Related

Newtonsoft.JSON null values when deserializing

I'm using .NET CORE 3.1 and Newtonsoft.Json to deserialize a JSON response from the API.
this is how the JSON response is structured from the API:
{
"PageSize": 200,
"PageCount": 1,
"RecordCount": 13,
"PageNumber": 1,
"Result": "OK",
"organization":[
{
"5LevelOrganization": {
"organizationLevel1Code": "xxxxxxxx",
"organizationLevel1Name": "Corporate Human Resources",
"organizationLevel2Code": "xxxxxxxx",
"organizationLevel2Name": "BHR Downstream & Midstream",
"organizationLevel3Code": "xxxxxxxx",
"organizationLevel3Name": "Chemicals",
"organizationLevel4Code": "",
"organizationLevel4Name": "",
"organizationLevel5Code": "xxxxxxxx",
"organizationLevel5Name": "Chemicals"
}
},
{
"5LevelOrganization": {
"organizationLevel1Code": "xxxxxxxx",
"organizationLevel1Name": "Corporate Human Resources",
"organizationLevel2Code": "xxxxxxxx",
"organizationLevel2Name": "BHR Downstream & Midstream",
"organizationLevel3Code": "xxxxxxxx",
"organizationLevel3Name": "Chemicals",
"organizationLevel4Code": "xxxxxxxx",
"organizationLevel4Name": "Americas Oronite Manufacturing HR",
"organizationLevel5Code": "xxxxxxxx",
"organizationLevel5Name": "Americas Oronite HR Managed"
}
}
]
}
This is how I structured the c# class with regards to the response:
public class _5LevelOrganization
{
[JsonPropertyName("organizationLevel1Code")]
public string OrganizationLevel1Code { get; set; }
[JsonPropertyName("organizationLevel1Name")]
public string OrganizationLevel1Name { get; set; }
[JsonPropertyName("organizationLevel2Code")]
public string OrganizationLevel2Code { get; set; }
[JsonPropertyName("organizationLevel2Name")]
public string OrganizationLevel2Name { get; set; }
[JsonPropertyName("organizationLevel3Code")]
public string OrganizationLevel3Code { get; set; }
[JsonPropertyName("organizationLevel3Name")]
public string OrganizationLevel3Name { get; set; }
[JsonPropertyName("organizationLevel4Code")]
public string OrganizationLevel4Code { get; set; }
[JsonPropertyName("organizationLevel4Name")]
public string OrganizationLevel4Name { get; set; }
[JsonPropertyName("organizationLevel5Code")]
public string OrganizationLevel5Code { get; set; }
[JsonPropertyName("organizationLevel5Name")]
public string OrganizationLevel5Name { get; set; }
}
public class Organization
{
[JsonPropertyName("5LevelOrganization")]
public _5LevelOrganization _5LevelOrganization { get; set; }
}
public class FiveLevel
{
[JsonPropertyName("PageSize")]
public int PageSize { get; set; }
[JsonPropertyName("PageCount")]
public int PageCount { get; set; }
[JsonPropertyName("RecordCount")]
public int RecordCount { get; set; }
[JsonPropertyName("PageNumber")]
public int PageNumber { get; set; }
[JsonPropertyName("Result")]
public string Result { get; set; }
[JsonPropertyName("organization")]
public List<Organization> Organization { get; set; }
}
The problem is when I try to deserialize the response JSON it always leads to having null values for 5LevelOrganization:
var fiveLevelResult = _5levelresponse.Content.ReadAsStringAsync().Result;
FiveLevel fivelevel = JsonConvert.DeserializeObject<FiveLevel>(fiveLevelResult);
Image for NULL 5LevelOrganization
Initially I thought the issue was with the JSON response property which starts with a number (5LevelOrganization) so I added the JsonPropertyAttribute but it still won't deserialize properly resulting to NULL. The response from the API is as expected.
I'm just wondering where I did wrong? Any help or information is greatly appreciated.
[JsonPropertyName] is a System.Text.Json attribute but you are trying to use a Newtonsoft.Json deserialiazer.
You have to change attribute to [JsonProperty] or to use a System.Text.Json deserializer
using System.Text.Json;
FiveLevel fivelevel = JsonSerializer.Deserialize<FiveLevel>(fiveLevelResult);
As what Llama said I was using the wrong attribute for the Serializer that I'm using when I switched [JsonPropertyName] to [JsonProperty] from the JSON.NET library the results is as expected.

Dynamic json property deserialize

I'm having difficulties figuring out how to deserialize a json, that has a dynamic property (for example - UserRequest::567) the property name can be any value and the UserRequest object contains other json properties that are of interest to me
I tired writing a class and I don't know what to do with that property. What are the best practices for coping with a problem like this?
{
"objects": {
"UserRequest::567": {
"code": 0,
"message": "created",
"class": "UserRequest",
"key": "567",
"fields": {
"ref": "R-000567",
"org_id": "4"
}
}
}
}
The question is what are the best practices to read through this kind of a json string?
Thank you
To Deserialize this using Newtonsoft.Json, here are the classes:
public class CreateRequest
{
public long code { get;set; }
public string message { get; set; }
[JsonProperty("class")]
public string class1 { get; set; }
public string key { get; set; }
public Fields fields { get; set; }
}
public class Fields
{
[JsonProperty("ref")]
public string refe { get; set; }
public string org_id { get; set; }
}
public class Root
{
public Dictionary<string, CreateRequest> objects { get; set; }
//The 'string' key in the dictionary is the 'UserRequest::567'
}
Then to Deserialize use:
var x = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(jsonObject).objects.Values;

JsonConvert deserialize only Class fields

This is json:
{
"odata.metadata": ".....",
"value": [
{
"AbsEntry": 10,
"ItemNo": "....",
"UoMEntry": -1,
"Barcode": "2000000000022",
"FreeText": "Ean13"
}
]
}
This is class:
public class BarCode
{
public int AbsEntry { get; set; }
public string ItemNo { get; set; }
public string Barcode { get; set; }
public string FreeText { get; set; }
}
This method return null:
BarCode barcode = JsonParser.DeserializeObjcet<BarCode>(json);
Are there any properties or other that can cause the call DeserializeObject to deserialize me only the fields of my classes (the names are exactly those of the Json)?
You need to create class like below not BarCode
public class Value
{
public int AbsEntry { get; set; }
public string ItemNo { get; set; }
public int UoMEntry { get; set; }
public string Barcode { get; set; }
public string FreeText { get; set; }
}
or you can change the JSON format
"BarCode": [
{
"AbsEntry": 10,
"ItemNo": "....",
"UoMEntry": -1,
"Barcode": "2000000000022",
"FreeText": "Ean13"
}
]
The structure of your class should match the structure of your JSON if you want the deserialization to succeed.
If you want a partial deserialization e.g. only deserializing the values property into your class you can use this code:
JObject jObject = JObject.Parse(json);
BarCode barcode = jObject["values"].Children().First().ToObject<BarCode>();
With this solution you don't need to refactor your class or adding a new one.
You are missing the root object :
public class RootObject
{
public string __invalid_name__odata.metadata { get; set; }
public List<BarCode> value { get; set; }
}
note that the invalid name oprperty can just be remove so it will be igrored!
Even if you want only the Value part you will have to deserialise from the root, then navigate to the child properties you need.

Deserialising JSON and child object to List<Class>

I've checked out a few questions on StackOverflow but can't find a method that works for me.
I'm essentially trying to deserialise the following JSON into a list of my "suppressedContact" class, but I can't get it to work.
The JSON looks like this:
[
{
"suppressedContact": {
"id": 23,
"email": "nelson.redeker#example.com",
"optInType": "Unknown",
"emailType": "PlainText",
"dataFields": null,
"status": "Unsubscribed"
},
"dateRemoved": "2015-09-18T15:26:25.2612537Z",
"reason": "Unsubscribed"
},
{
"suppressedContact": {
"id": 25,
"email": "terry.mccarthy#example.com",
"optInType": "VerifiedDouble",
"emailType": "Html",
"dataFields": null,
"status": "Unsubscribed"
},
"dateRemoved": "2015-02-24T13:06:42.933Z",
"reason": "Unsubscribed"
},
]
The class I am trying to deserialise into looks like this:
public class SuppressedRoot
{
public Suppressedcontact suppressedContact { get; set; }
public DateTime dateRemoved { get; set; }
public string reason { get; set; }
}
public class Suppressedcontact
{
public int id { get; set; }
public string email { get; set; }
public string optInType { get; set; }
public string emailType { get; set; }
public object dataFields { get; set; }
public string status { get; set; }
}
I'm using this piece of code to attempt to accomplish this:
List<Suppressedcontact> unsubscribedContacts = JsonConvert.DeserializeObject<List<Suppressedcontact>>(jsonResponse);
This however does not work.
Any help in this would be appreciated, I'm trying to get to a stage where I can loop through all of the returned contacts and extract the email addresses.
Try replacing
List<Suppressedcontact> unsubscribedContacts = JsonConvert.DeserializeObject<List<Supporesscontact>>(jsonResponse);
with
List<SuppressedRoot> unsubscribedContacts = JsonConvert.DeserializeObject<List<SuppressedRoot>>(jsonResponse);

Parsing nested JSON objects with JSON.NET

My JSON feed has nested objects like this:
{
"id": 1765116,
"name": "StrozeR",
"birth": "2009-08-12",
"avatar": "http:\/\/static.erepublik.com\/uploads\/avatars\/Citizens\/2009\/08\/12\/f19db99e9baddad73981d214a6e576ef_100x100.jpg",
"online": true,
"alive": true,
"ban": null,
"level": 61,
"experience": 183920,
"strength": 25779.42,
"rank": {
"points": 133687587,
"level": 63,
"image": "http:\/\/www.erepublik.com\/images\/modules\/ranks\/god_of_war_1.png",
"name": "God of War*"
},
"elite_citizen": false,
"national_rank": 6,
"residence": {
"country": {
"id": 81,
"name": "Republic of China (Taiwan)",
"code": "TW"
},
"region": {
"id": 484,
"name": "Hokkaido"
}
}
}
and my object classes are like this:
class Citizen
{
public class Rank
{
public int points { get; set; }
public int level { get; set; }
public string image { get; set; }
public string name { get; set; }
}
public class RootObject
{
public int id { get; set; }
public string name { get; set; }
public string avatar { get; set; }
public bool online { get; set; }
public bool alive { get; set; }
public string ban { get; set; }
public string birth { get; set; }
public int level { get; set; }
public int experience { get; set; }
public double strength { get; set; }
public List<Rank> rank { get; set; }
}
}
I try to parse my JSON data with following code
private async void getJSON()
{
var http = new HttpClient();
http.MaxResponseContentBufferSize = Int32.MaxValue;
var response = await http.GetStringAsync(uri);
var rootObject = JsonConvert.DeserializeObject<Citizen.RootObject>(response);
uriTB.Text = rootObject.name;
responseDebug.Text = response;
}
but I get the following error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Erepublik.Citizen+Rank]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
I can't even parse the value in the main object. Anyway to fix this? and how can I parse a value inside of a nested object? for example: "points" in "rank"
Like the error message says, your rank property in the .NET class is a List<Rank>, but in your JSON it's just a nested object, not an array. Change it to just a Rank instead of a List<Rank>.
Arrays in JSON (or any Javascript, really) are enclosed in []. The {} characters specify a single object. The CLR type has to roughly match the JSON type in order to deserialize. Object to object, array to array.

Categories