Deserialize JSON object structure with ids as keys [duplicate] - c#

This question already has answers here:
How can I deserialize a child object with dynamic (numeric) key names?
(2 answers)
Closed 7 years ago.
I have this JSON that is generated by a third party web service
{
"user_data": {
"123456789": {
"transactions_id": 123456789,
"transaction_date": "2015-07-08T18:31:28+01:00",
"reason_type": "REWARD",
"category": "categoryFoo",
"title": "titleFoo",
"description": "",
"reward_quantity": 5,
"reward_name": " foo"
},
"1234567891": {
"transactions_id": 1234567891,
"transaction_date": "2015-07-08T18:33:06+01:00",
"reason_type": "REWARD",
"category": "categoryFoo",
"title": "titleFoo",
"description": "",
"reward_quantity": 5,
"reward_name": " foo"
},
"1234567892": {
"transactions_id": 1234567892,
"transaction_date": "2015-07-08T18:35:00+01:00",
"reason_type": "REWARD",
"category": "categoryFoo",
"title": "titleFoo",
"description": "",
"reward_quantity": 5,
"issuers_name": " foo"
}
}
}
The amount of transactions will change with each request so there may be 3 like this one time and then 10 the next. To handle the varying numbers of transactions I understand that you would need to use a list similar to this public List<User> users { get; set; } with users being similar to this
public class User
{
public int transactions_id { get; set; }
public string transaction_date { get; set; }
public string reason_type { get; set; }
public string category { get; set; }
public string title { get; set; }
public string description { get; set; }
public int reward_quantity { get; set; }
public string reward_name { get; set; }
}
However I do think this will work because of the weird structure of the JSON where each "transaction" has it ID as its name. Sorry I'm not sure of the correct terminology but I think you should be able to get the gist.

This isn't a particularly unusual structure in JSON. That should be deserialized to a Dictionary<string, User>:
public class Root
{
[JsonProperty("user_data")]
public Dictionary<string, User> Users { get; set; }
}
Then just use JsonConvert.DeserializeObject<Root> as normal.
Note how I'm using JsonProperty to specify how the name is represented in JSON while keeping idiomatic .NET property names - I suggest you do that in your User class too.

public class UserData
{
[JsonProperty("user_data")]
public Dictionary<string, User> Users { get; set; }
}

Related

deserializing dynamic named JSON attributes to a C# class

{
"Documents": {
"c97bba6f-c8ab-4453-91f8-f663f478910c": {
"id": "c97bba6f-c8ab-4453-91f8-f663f478910c",
"name": "name",
"sys": {
"c67bfa6f-c8ab-4453-91f8-f663f478910c": {
"id": "c97bba6f-c8ab-4453-91f8-f663f478910c",
"name": "sys name"
},
"a67bfa6f-c8ab-4453-91f8-f663f478910c": {
"id": " a67bfa6f-c8ab-4453-91f8-f663f478910c",
"name": "sys name"
}
}
},
"f97bba6f-c8ab-4453-91f8-f663f478910c": {
"id": "c97bba6f-c8ab-4453-91f8-f663f478910c",
"name": "OZL - B - MECH - AC - Fan Coil Units",
"sys": {}
}
}
}
I've got JSON data in the form above and am having trouble deserializing this into a C# class. The trouble I'm having is that the GUID is used to define the object that the Documents object has rather than the documents object having a list of documents.
I've tried to create a documents object that has a list of object in it and deserialise into this using Newtonsoft. I've also tried a dictionary of string, object in the documents object. None of these work.
Any input or ideas would be most appreciated.
Edit: the biggest issue I'm having is the nesting of Dictionary<GUID, object>. Newtonsoft won't map to the dictionary within the first object. Here's what I have:
public class Documents {
public dictionary<Guid, System> data { get; set; }
}
public class System {
public Guid Id { get; set;}
public string Name { get; set; }
public dictionary<guid, someOtherobject> otherData { get; set;}
}
Based on your JSON, the class structure you need is this:
public class RootObject
{
public Dictionary<Guid, Document> Documents { get; set; }
}
public class Document
{
public Guid Id { get; set; }
public string Name { get; set; }
public Dictionary<Guid, Sys> Sys { get; set; }
}
public class Sys
{
public Guid Id { get; set; }
public string Name { get; set; }
}
Then deserialize into the RootObject class like this:
var root = JsonConvert.DeserializeObject<RootObject>(json);
Here is a working demo: https://dotnetfiddle.net/Uycomw

Resolve Json Key Value pair to POCO Properties [duplicate]

This question already has answers here:
Deserialize array of key value pairs using Json.NET
(5 answers)
Closed 2 years ago.
I receive a Json that looks like this:
[
{
"FieldName": "Note",
"Value": "Test of a note"
},
{
"FieldName": "P&IPayment",
"Value": "Payment amount"
},
{
"FieldName": "000-002",
"Value": "ABC"
},
]
I want to deserialize it to a class that looks like this:
public class ExportModel
{
[Newtonsoft.Json.JsonPropertyAttribute("Note")]
public string Note { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("P&IPAYMENT")]
public string PAndIPayment { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("000-002")]
public string MajorLoanType { get; set; }
}
I want the FieldName to map to the attribute of the property and the Value to map to the property.
Thank you for any help.
You have to change the name of values:
[Newtonsoft.Json.JsonPropertyAttribute("Note")]
public string Note { get; set; } CHANGE FOR --->
[Newtonsoft.Json.JsonPropertyAttribute("FieldName")]
public string FieldName { get; set; }
[Newtonsoft.Json.JsonPropertyAttribute("P&IPAYMENT")]
public string P&IPAYMENT{ get; set; } CHANGEFOR--->
[Newtonsoft.Json.JsonPropertyAttribute("Value")]
public string Value{ get; set; }
And you have to delete these lines of code:
[Newtonsoft.Json.JsonPropertyAttribute("000-002")]
public string MajorLoanType { get; set; }

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;

JSON deserialize variable number of properties

I have a JSON class structure like this from a third party API (only the problem part shown):
"template": {
"name": "MovieTemplate",
"ruleName": "Movie Template",
"zones": {
"Products": {
"type": "Record",
"name": "Products",
"content": "www.imagescloudsite.com/blahblah.gif"
"records": [ … ]
},
"URL": {
"type":"DVD",
"name":"Bundle"
"content": "www.imagescloudsite.com/blahblah.gif"
}
}
}
The "zones" property can contain many properties "Products","URL","Superman","Descartes",etc...
But, I do not know which ones and how many will be there, because these are added by our content guys in a special control panel. Newtonsoft Deserializer complains because I have a model like this and it clearly does not capture the zone name like 'Products' and 'URL':
public class Zone
{
public string Type { get; set; }
public string Name { get; set; }
public string Content { get; set; }
}
public class Template
{
public string Name { get; set; }
public string RuleName { get; set; }
public List<Zone> Zones { get; set; }
}
Any ideas on how I can capture the zone names using NewtonSoft?
Thanks.
Turn your Zone property to a dictionary since you don't know the keys in before hand, but do know their content structure.
Like so
public class Template
{
public string Name { get; set; }
public string RuleName { get; set; }
public Dictionary<string,Zone> Zones { get; set; }
}
What if you changed the Template class to the following:
public class Template
{
public string Name { get; set; }
public string RuleName { get; set; }
public Dictionary<string, Zone> Zones { get; set; }
}
You could then access the name via the key of the entry.
Use of dynamic would be a good bet
dynamic d = Newtonsoft.Json.Linq.JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");

Json.NET Serializing my object gives me the wrong output

I'm having a bit of a problem with serializing my .NET objects into JSON using JSON.NET. The output I want to be serialized will have to look like this:
{"members":[
{"member":
{
"id":"4282",
"status":"1931",
"aktiv":"1",
"firmanavn":"firmname1",
"firmaUrl":"www.firmurl.dk",
"firmaUrlAlternativ":"",
"firmaSidstKontrolleretDato":"30-08-2010",
"firmaGodkendelsesDato":"07-03-2002"
}
},
{"member":
{
"id":"4283",
"status":"1931",
"aktiv":"1",
"firmanavn":"firmname2",
"firmaUrl":"www.firmurl.dk",
"firmaUrlAlternativ":"",
"firmaSidstKontrolleretDato":"30-08-2010",
"firmaGodkendelsesDato":"18-12-2000"
}
},
...... long list of members omitted
My .NET structure for now (still experimenting to get the right output) is like this:
public class Members
{
public List<Member> MemberList { get; set; }
}
and:
public class Member
{
[JsonProperty(PropertyName = "Id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Status")]
public string Status { get; set; }
[JsonProperty(PropertyName = "Aktiv")]
public string Aktiv { get; set; }
[JsonProperty(PropertyName = "Firmanavn")]
public string Firmanavn { get; set; }
[JsonProperty(PropertyName = "FirmaUrl")]
public string FirmaUrl { get; set; }
[JsonProperty(PropertyName = "AltFirmaUrl")]
public string AlternativFirmaUrl { get; set; }
[JsonProperty(PropertyName = "FirmaSidstKontrolleretDato")]
public string FirmaSidstKontrolleretDato { get; set; }
[JsonProperty(PropertyName = "FirmaGodkendelsesDato")]
public string FirmaGodkendelsesDato { get; set; }
}
What the above .NET structure gives me when calling:
string json = JsonConvert.SerializeObject(members, Newtonsoft.Json.Formatting.Indented);
Where 'members' is a list of members. Is this:
{
"Members": [
{
"Id": "1062",
"Status": "1933",
"Aktiv": "1",
"Firmanavn": "firmname",
"FirmaUrl": "http://www.firmurl.dk",
"AltFirmaUrl": "http://www.altfirmurl.dk",
"FirmaSidstKontrolleretDato": "13-09-2011",
"FirmaGodkendelsesDato": "13-09-2511"
},
{
"Id": "1060",
"Status": "1933",
"Aktiv": "1",
"Firmanavn": "firmname2",
"FirmaUrl": "http://www.firmurl.dk",
"AltFirmaUrl": "http://www.altfirmurldk",
"FirmaSidstKontrolleretDato": "13-09-2011",
"FirmaGodkendelsesDato": "13-09-2511"
},
So basically, the structure is right in that it creates the array of members as expected, but I am missing the "member": label on each of the member objects. Is there any way to make such a label? Some kind of class declaration, or something?
I hope my question is clear, if not - please let me know and I'll try to explain further.
Thanks a lot in advance.
/ Bo
It sounds like you just need to make an intermediary object with a property of that name to get the JSON you want; however, I'd consider using the JSON.net originally rendered JSON (as it is structurally better).

Categories