How to get inner field's value of object by using JsonProperty - c#

I have data in json like this:
{
"data": {
"name" : "Car wash"
"changed_by": {
"id": 1,
"name": "Pascal",
"type": "user"
}
}
}
The value "Car wash" I can get like this:
public class Changes
{
[JsonProperty("name")]
public string name { get; set; }
}
How I can get the value of some changed_by object field?
I need to use this in deserializing
private void GetChanges(RawData data)
{
var changes = JsonConvert.DeserializeObject<Response<IEnumerable<Model.Json.Changes>>>(data.ChangesData);
/* some code */
}

You just need to have a class that represents the changed_by object. For example:
public class Data
{
public string name { get; set; }
public ChangedBy changed_by { get; set; }
}
public class ChangedBy
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
}

Create a class hierarchy representing the structure of the data in and then use Json.Net to deserialize it into an object of this class.
Check out Json.Net

Related

Deserializing JSON when inner property names vary

I have JSON which looks something like this (external JSON beyond my control):
[
{
"currencies": {
"KGS": {
"name": "Kyrgyzstani som",
"symbol": "с"
}
}
},
{
"currencies": {
"SOS": {
"name": "Somali shilling",
"symbol": "Sh"
}
}
}
]
And I have a set of classes which I would like this JSON deserialized into
public class ParentClass
{
public OuterClass Currencies { get; set; }
}
public class OuterClass
{
//Inner property below needs to map to these changing prop names: "KGS", "SOS"
public InnerClass Inner { get; set; }
}
public class InnerClass
{
public string Name { get; set; }
public string Symbol { get; set; }
}
And Lastly, when I try to deserialize:
JsonConvert.DeserializeObject<IList<ParentClass>>(responseBody.Content);
It's not deserializing properly, because the it cannot map varying Property names to "Inner". Is there a way to handle this scenario?
Newtonsoft didn't seem to have any problem with it..
public partial class Blah
{
[JsonProperty("currencies")]
public Dictionary<string, Currency> Currencies { get; set; }
}
public partial class Currency
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("symbol")]
public string Symbol { get; set; }
}
And
var blah = JsonConvert.DeserializeObject<Blah[]>(jsonString);
..though it's probably worth noting I think you have your parent and outer the wrong way round if this json is just a fragment..

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; }
}

Prevent serialize property name in json

I have two classes.
First one is:
public int id { get; set; }
public List<AnotherClass> field1 { get; set; }
And the second one is
public class AnotherClass
{
[JsonIgnore]
public int id { get; set; }
public string subfieldValue { get; set; }
}
when I make object from these classes and serialize them I get below JSON from them
{
"id" : "1",
"field1": [
{
"subfieldValue":"value1"
},
{
"subfieldValue":"value2"
}
]
}
But I need below JSON how can I do that? Also I can't use List<string> for field1 type because I want to save this values to database with Entity Framework
{
"id" : "1",
"field1": ["value1", "value2"]
}
public int id { get; set; }
[JsonIgnore]
public List<AnotherClass> field1s { get; set; }
public List<string> field1
{
get{return field1s.Select(f=>f. subfieldValue).ToList();}
set{}
}
Also you probably should maintain the common C# naming convention like Id instead of id and change the json name through attribute with whatever you like in your json.

Categories