How to serialize List<object> with dedicated name to JSON? - c#

I'm pretty new to json so this might be a duplicate. I apologize in advance, but I just don't know how to search for this.
I have the following json file that I have to serialize:
{
"filename":"myFileName.txt",
"sourceProperties":{
"properties":[
{
"key": "myKey0",
"value": "myValue0"
},
{
"key": "myKey1",
"value": "myValue1"
}
]
},
}
I declared two classes to resemble that object:
class Document
{
[JsonProperty(PropertyName = "filename")]
public string Filename { get; set; }
[JsonProperty(PropertyName = "sourceProperties")]
public List<DocProperty> Properties { get; set; }
}
class DocProperty
{
[JsonProperty(PropertyName = "key")]
public string Key { get; set; }
[JsonProperty(PropertyName = "value")]
public string Value { get; set; }
}
But of course the lists tag "properties", which is required in the json file, does not show.
What is the correct way to declare my object, that I get the "sourceProperties" tag, followed by the "properties" tag and list?

Something like this:
class Document
{
[JsonProperty(PropertyName = "filename")]
public string Filename { get; set; }
[JsonProperty(PropertyName = "sourceProperties")]
public SourceProperties Source { get; set; }
}
class SourceProperties
{
[JsonProperty(PropertyName = "properties")]
public Dictionary<string, string> Properties { get; set; }
}
I intentionally replaced List<DocProperty> by Dictionary class, because it's format self-descriptive, and matches structure of your JSON file, but you can use List<DocPropety> if you really want.

Related

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.

How do you deserialize json into a C# object that has "#" at the beginning of the property names?

I am having trouble deserializing json I have that has an # symbol at the beginning of a lot of the property names. It is a lot of json so I don't know if just removing all # from the json is safe or if I would lose some valuable information in the values associated with properties.
I tried using a [JsonProperty("#fontName")], for example, but that didn't work (the C# object did not adopt the value I see in the JSON; it was null instead).
internal static RootObject MyMethod(string json)
{
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
return rootObject;
}
Here is a snippet of the json I'm dealing with:
{
"document": {
"page": [
{
"#index": "0",
"row": [
{
"column": [
{
"text": ""
},
{
"text": {
"#fontName": "Times New Roman",
"#fontSize": "8.0",
"#x": "133",
"#y": "14",
"#width": "71",
"#height": "8",
"#text": "FINAL STATEMENT"
}
...
Here is an example of what I want to deserialize into:
public class Column
{
[JsonProperty("#fontName")]
public string fontName { get; set; }
public object text { get; set; }
}
public class Row
{
public List<Column> column { get; set; }
public string text { get; set; }
}
public class Page
{
public string index { get; set; }
public List<Row> row { get; set; }
public string text { get; set; }
}
public class Document
{
public List<Page> page { get; set; }
}
public class RootObject
{
public Document document { get; set; }
}
From what I see you miss one of your properties index property of your Page object.
Write it this way [JsonProperty(PropertyName ="#index")] it is better to understand. Also we don't see the definition of fontName, fontSize, x, y and so on, in separate Text class. For some reason you wrote it as just as object.
public class Text
{
[JsonProperty(PropertyName ="#fontName")]
public string FontName {get; set;}
[JsonProperty(PropertyName ="#fontSize")]
public string FontSize {get; set;}
[JsonProperty(PropertyName ="#text")]
public string TextResult{get; set;}
//other objects
}
public class Column
{
public List<Text> text { get; set; }
}

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