Deserializing a complex JSON object - c#

I use JavaScript.Serializer.Deserializer to deserialize a complex JSON object, as below:
{
"name": "rule 1",
"enabled": true,
"conditions": [{
"type": "time",
"time": "17:23:10",
"days": "125"
}, {
"type": "sensor",
"uid": "10.2.0.1",
"setpoint1": 12,
"setpoint2": 18,
"criterion": 1
}, {
"type": "sensor",
"uid": "10.3.0.1",
"setpoint1": 12,
"setpoint2": 18,
"criterion": 2
}],
"actions": {
"period": 100,
"single": false,
"act": [{
"type": "on",
"uid": "10.1.0.1"
}, {
"type": "sms",
"message": "Hello World"
}]
}
}
And I want to convert it to some classes, like below:
public class Rule
{
public string name { get; set; }
public bool enabled { get; set; }
public List<Condition> conditions { get; set; }
public List<Action> actions { get; set; }
}
public class Condition
{
public string type { get; set; }
public string uid { get; set; }
public DateTime? time { get; set; }
public string days { get; set; }
public double setpoint1 { get; set; }
public double setpoint2 { get; set; }
public int criterion { get; set; }
}
public class Action
{
public int period { get; set; }
public bool single { get; set; }
public List<Act> act { get; set; }
}
public class Act
{
public string type { get; set; }
public string uid { get; set; }
public string message { get; set; }
}
The deserialization snippet:
json = new JavaScriptSerializer();
Rule rule = (json.Deserialize<Rule>(jsonStr));
If I simplify the Rule class and declare conditions and actions as simple strings, it works fine.
But if I use the classes like above, it throws an exception:
Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[IoTWebApplication.Condition]'

The structure you create does not fit to the JSON you posted.
It should look like
public class Rule
{
public string name { get; set; }
public bool enabled { get; set; }
public Condition[ ] conditions { get; set; }
public Actions actions { get; set; }
}
public class Actions
{
public int period { get; set; }
public bool single { get; set; }
public Act[ ] act { get; set; }
}
public class Act
{
public string type { get; set; }
public string uid { get; set; }
public string message { get; set; }
}
public class Condition
{
public string type { get; set; }
public string time { get; set; }
public string days { get; set; }
public string uid { get; set; }
public int setpoint1 { get; set; }
public int setpoint2 { get; set; }
public int criterion { get; set; }
}
It is (in most cases) very easy in VS to get the classes direct out of the JSON
Copy JSON to clipboard
In VS EDIT/Special Paste/Paste JSON as Classes (the code above was created by this)

The problem was that the inner (nested) json was quoted and therefore was processed as a string. So when I removed the quotes, it worked fine:
json = new JavaScriptSerializer();
Rule rule = (json.Deserialize<Rule>(jsonStr));

Related

Why different results when deserializing objects?

I noticed that I would get different results when deserializing objects different ways. I must have missed something but couldn't figure out what.
Here is the json:
{
"content_version": "1",
"date_created": "2020-10-06T13:52:15.288Z",
"date_updated": "2020-10-06T13:54:24.325Z",
"content": {
"EN": {
"name_full": {
"text": "Test"
},
"name_short": {
"text": "TEST"
}
}
},
"tools": {
"car": true,
"truck": true,
"fleet": {
"use": true,
"languages": [
{
"fileName": "file1.json",
"name": {
"text": "English"
}
}
]
}
}
}
The following are the classes that I generated using a tool:
public class Root
{
public string content_version { get; set; }
public DateTime date_created { get; set; }
public DateTime date_updated { get; set; }
public ContentRootObject content { get; set; }
public Tools tools { get; set; }
}
public class ContentRootObject
{
[JsonProperty(PropertyName = "content")]
public Dictionary<string, ContentItem> DataItems { get; set; }
}
public class ContentItem
{
public NameFull name_full { get; set; }
public NameShort name_short { get; set; }
}
public class Tools
{
public bool car { get; set; }
public bool truck { get; set; }
public Fleet fleet { get; set; }
}
public class NameFull
{
public string text { get; set; }
}
public class NameShort
{
public string text { get; set; }
}
public class EN
{
public NameFull name_full { get; set; }
public NameShort name_short { get; set; }
}
public class Name
{
public string text { get; set; }
}
public class Language
{
public string fileName { get; set; }
public Name name { get; set; }
}
public class Fleet
{
public bool use { get; set; }
public List<Language> languages { get; set; }
}
and here is the code that I tried for deserializing :
var objTool = Newtonsoft.Json.JsonConvert.DeserializeObject<Tools>(json);
var objRoot = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(json);
var objContent = Newtonsoft.Json.JsonConvert.DeserializeObject<ContentRootObject>(json)
and here is what I got for each of the objects:
objTool: 'fleet' was returned as null in 'tools'
objRoot: the DataItems of 'content' was null.
objContent: got an error saying "Unexpected character encountered while parsing value: {. Path 'content.EN', line 1, position 146."
Although I can just deserialize the whole thing, I only need objTool and objContent and I was wondering what I did wrong in the above code? Thanks!
The issue is that the class that you have as a wrapper for the dictionary is not represented in the JSON. It'll deserialize the dictionary if you change the root object to this:
public class Root
{
public string content_version { get; set; }
public DateTime date_created { get; set; }
public DateTime date_updated { get; set; }
public Dictionary<string, ContentItem> content { get; set; }
public Tools tools { get; set; }
}

Why is my inner array not being deserialized?

I have some JSON which I'd like to deserialize into Objects.
I'm trying to do it like this, but I only get some of the JSON deserialized and the vin and vout JSON are either 0s or nulls. What am I doing wrong?
Transaction t = JsonConvert.DeserializeObject<RPCResponse<Transaction>>(json).result;
JSON:
{
"result": {
"hex": "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac00000000",
"txid": "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098",
"hash": "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098",
"size": 134,
"version": 1,
"locktime": 0,
"vin": [
{
"coinbase": "04ffff001d0104",
"sequence": 4294967295
}
],
"vout": [
{
"value": 50.00000000,
"n": 0,
"scriptPubKey": {
"asm": "0496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858ee OP_CHECKSIG",
"hex": "410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac",
"reqSigs": 1,
"type": "pubkey",
"addresses": [
"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX"
]
}
}
],
"blockhash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048",
"confirmations": 563356,
"time": 1231469665,
"blocktime": 1231469665
},
"error": null,
"id": "getrawtransaction"
}
The output in the debugger looks like this:
My Classes look like this:
public class RPCResponse<T>
{
public T result { get; set; }
public string error { get; set; }
public string id { get; set; }
}
public class Transaction
{
public string TxId { get; set; }
public long Size { get; set; }
public long Version { get; set; }
public long LockTime { get; set; }
public TransactionInputCoinbase[] Vin { get; set; }
public TransactionOutput[] Vout { get; set; }
public string BlockHash { get; set; }
public long Time { get; set; }
}
public class TransactionInputCoinbase
{
string Coinbase { get; set; }
string Sequence { get; set; }
}
public class TransactionOutput
{
decimal Value { get; set; }
int N { get; set; }
ScriptPubKey ScriptPubKey { get; set; }
}
public class ScriptPubKey
{
string Asm { get; set; }
string Hex { get; set; }
long ReqSigs { get; set; }
string Type { get; set; }
string[] Addresses { get; set; }
}
The lack of public properties on the said objects
For example
public class TransactionInputCoinbase
{
string Coinbase { get; set; } //<--NOT PUBLIC
string Sequence { get; set; } //<--NOT PUBLIC
}
means those properties will never be set when initialized via deserialization.
The same goes for TransactionOutput and ScriptPubKey based on the code originally provided.

using DataContractJsonSerializer knowntype

I am trying to deserealize json:
Classes is generated by json2sharp
But it throws exception:
Element ": Data" contains data from a data type that maps to the name
"http://schemas.datacontract.org/2004/07/TMSoft.CryptoDoc.Gu45:Gu45".
The deserializer is no information of any type, are matched with the
same name. Use DataContractResolver or add type that matches "Gu45",
the list of known types, such as using KnownTypeAttribute attribute or
by adding it to the list of known types passed to
DataContractSerializer.
How to fix it?
namespace json
{
class Program
{
static void Main(string[] args)
{
string json = System.IO.File.ReadAllText(#"D:\Json.txt");
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RootObject));
var account = serializer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
}
}
public class Branch
{
public string Code { get; set; }
public string Name { get; set; }
}
public class Direction
{
public object Code { get; set; }
public string Name { get; set; }
}
public class Org
{
public string Code { get; set; }
public string Name { get; set; }
}
public class Wagon
{
public string Comment { get; set; }
public object NoteTimeString { get; set; }
public string Number { get; set; }
public string OwnerCode { get; set; }
public string StateString { get; set; }
}
public class Data
{
public string __type { get; set; }
public Branch Branch { get; set; }
public string DeliveryTimeString { get; set; }
public Direction Direction { get; set; }
public string EsrCode { get; set; }
public int GU45Type { get; set; }
public object ManeuverTime { get; set; }
public string Number { get; set; }
public Org Org { get; set; }
public object ParkName { get; set; }
public object ParkNum { get; set; }
public string RailwayName { get; set; }
public string RegistrationDateTimeString { get; set; }
public object Span { get; set; }
public string StationName { get; set; }
public string TakingTimeString { get; set; }
public object TrackNum { get; set; }
public object TrackNumAddition { get; set; }
public object WagonNote { get; set; }
public List<Wagon> Wagons { get; set; }
}
public class Body
{
public Data Data { get; set; }
public List<int> Signature { get; set; }
}
public class RootObject
{
public Body Body { get; set; }
public int Revision { get; set; }
public int State { get; set; }
public string StateDate { get; set; }
public string WosId { get; set; }
}
}
Json.txt:
{
"Body": {
"Data": {
"__type": "Gu45:#TMSoft.CryptoDoc.Gu45",
"Branch": {
"Code": "9898",
"Name": "Place"
},
"DeliveryTimeString": "07.03.2014 10:00:00",
"Direction": {
"Code": null,
"Name": "Test"
},
"EsrCode": "320007",
"GU45Type": 2,
"ManeuverTime": null,
"Number": "1",
"Org": {
"Code": "1860",
"Name": "Test"
},
"ParkName": null,
"ParkNum": null,
"RailwayName": "Test",
"RegistrationDateTimeString": "07.03.2014",
"Span": null,
"StationName": "Test",
"TakingTimeString": "07.03.2014 12:00:00",
"TrackNum": null,
"TrackNumAddition": null,
"WagonNote": null,
"Wagons": [
{
"Comment": "РЕМТ",
"NoteTimeString": null,
"Number": "44916989",
"OwnerCode": "22",
"StateString": "0"
}
]
},
"Signature": [
48,
106
]
},
"Revision": 1966,
"State": 2,
"StateDate": "2014-03-07T12:48:03Z",
"WosId": "15805729"
}
I had similar experience in my previous projects with DataContractJsonSerializer. it seems that "__type" field has a special meaning for DataContractJsonSerializer.
This is one of the main reasons that I use Json.net
it matters only if it's the first property in the object but if it has any other positions it works and exceptions is not thrown. you can try it but changing __type position below the branch property in Json.txt. I don't know if it's the case and you can find a workaround.
I haven't tried this solution but it worth to give it a try:
hope it helps

Retrieve the values from json string

I have json string. I want to retrieve the contact from json string. Following json contains array of contacts. here is my json string.
{
   "contacts": {
      "contact": [
         {
            "isConnection": false,
            "id": 33554611,
            "fields": [
               {
                  "id": 33554748,
                  "type": "name",
                  "value": {
                     "givenName": "Jhon",
                     "middleName": "",
                     "familyName": "Scot",
                     "prefix": "",
                     "suffix": "",
                     "givenNameSound": "",
                     "familyNameSound": ""
                  },
                  "editedBy": "OWNER",
                  "flags": [],
                  "categories": [],
                  "updated": "2012-12-23T07:40:23Z",
                  "created": "2012-12-23T07:40:23Z",
               },
               {
                  "id": 33554749,
                  "type": "email",
                  "value": "someone#example.com",
                  "editedBy": "OWNER",
                  "flags": [],
                  "categories": [],
                  "updated": "2012-12-23T07:40:23Z",
                  "created": "2012-12-23T07:40:23Z",
               }
            ]
         }
}
}
Here I want to retrieves the values of givenName,familyName,email. How can I retrieve the values of these from json string.
Note: there are array of contact in json. I have posted only one contact from this json.
I tried something like this. But not worked.
JObject json = JObject.Parse(returnStr);
JArray fields = (JArray)json["contacts"]["contact"]["fields"][0];
JArray FValues = (JArray)json["contact"]["fields"]["value"];
I tried this
public class Field
{
public int id { get; set; }
public string type { get; set; }
public object value { get; set; }
public string editedBy { get; set; }
public List<object> flags { get; set; }
public List<object> categories { get; set; }
public string updated { get; set; }
public string created { get; set; }
public string uri { get; set; }
public bool? isConnection { get; set; }
}
public class contact
{
public bool isConnection { get; set; }
public int id { get; set; }
public List<Field> fields { get; set; }
public List<object> categories { get; set; }
public int error { get; set; }
public int restoredId { get; set; }
public string created { get; set; }
public string updated { get; set; }
public string uri { get; set; }
}
public class Contacts
{
public List<contact> contact { get; set; }
public int count { get; set; }
public int start { get; set; }
public int total { get; set; }
public string uri { get; set; }
public bool cache { get; set; }
}
public class RootObject
{
public Contacts contacts { get; set; }
}
and
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
RootObject obje = serializer1.Deserialize<RootObject>(returnStr);
But it is giving me 0 value in obje.
First make sure your Json is in valid format using jsonlint
Then generate class base on it using json2csharp
public class Field
{
public int id { get; set; }
public string type { get; set; }
public object value { get; set; }
public string editedBy { get; set; }
public List<object> flags { get; set; }
public List<object> categories { get; set; }
public string updated { get; set; }
public string created { get; set; }
}
public class Contact
{
public bool isConnection { get; set; }
public int id { get; set; }
public List<Field> fields { get; set; }
}
public class Contacts
{
public List<Contact> contact { get; set; }
}
public class RootObject
{
public Contacts contacts { get; set; }
}
Use Newtonsoft JSON to deserialize your Json into object(s) then you may simply access its properties value.
JsonConvert.DeserializeObject<RootObject>(string json);
Class for json object (generated with http://jsonutils.com/ after correcting some syntax error):
public class Field
{
public int id { get; set; }
public string type { get; set; }
public object value { get; set; }
public string editedBy { get; set; }
public IList<object> flags { get; set; }
public IList<object> categories { get; set; }
public DateTime updated { get; set; }
public DateTime created { get; set; }
}
public class Contact
{
public bool isConnection { get; set; }
public int id { get; set; }
public IList<Field> fields { get; set; }
}
public class Contacts
{
public IList<Contact> contact { get; set; }
}
public class Example
{
public Contacts contacts { get; set; }
}
Deserialization (you will probably need to add a reference to System.Web.Extensions):
System.Web.Script.Serialization.JavaScriptSerializer deSer = new System.Web.Script.Serialization.JavaScriptSerializer();
JSonPrintSettingsToXml.Input.Example deserializedJSON = deSer.Deserialize<JSonPrintSettingsToXml.Input.Example>(yourJSON);
Here is the corrected JSON
{
"contacts": {
"contact": [
{
"isConnection": false,
"id": 33554611,
"fields": [
{
"id": 33554748,
"type": "name",
"value": {
"givenName": "Jhon",
"middleName": "",
"familyName": "Scot",
"prefix": "",
"suffix": "",
"givenNameSound": "",
"familyNameSound": ""
},
"editedBy": "OWNER",
"flags": [],
"categories": [],
"updated": "2012-12-23T07:40:23Z",
"created": "2012-12-23T07:40:23Z"
},
{
"id": 33554749,
"type": "email",
"value": "someone#example.com",
"editedBy": "OWNER",
"flags": [],
"categories": [],
"updated": "2012-12-23T07:40:23Z",
"created": "2012-12-23T07:40:23Z"
}
]
}
]
}
}
You need to go with the following structure:
public class Contact
{
public bool isConnection { get; set; }
public int id { get; set; }
public List<Field> fields { get; set; }
}
public class Field
{
public int id { get; set; }
public string type { get; set; }
public object value { get; set; }
public string editedBy { get; set; }
public string[] flags { get; set; }
public string[] categories { get; set; }
public DateTime updated { get; set; }
public DateTime created { get; set; }
}
public class Name
{
public string givenName { get; set; }
public string middleName { get; set; }
public string familyName { get; set; }
public string prefix { get; set; }
public string suffix { get; set; }
public string givenNameSound { get; set; }
public string familyNameSound { get; set; }
}
And then deserialize it and use LINQ to manipulate fields.
If you want to stick to JObject and not create classes, look at the example provided at http://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing
You'll have to enumerate over this
dynamic contacts = (JArray)json["contacts"]
foreach(dynamic contact in contacts.contact) {
// look at the fields...
}
PS. Give it a go, don't have VS on me so cant quite verify the exact syntax
Firstly, I think you'll find that your JSON is not well-formed. You don't need the extra commas after the two "created" dates and there is a right-square bracket missing before the second last curly brace. I recommend you always validate your JSON using this awesome site: http://jsonformatter.curiousconcept.com
Secondly, you are not referencing the array elements correctly. Although I agree with #grundy that you should be creating class definitions for managing JSON and using LINQ, there is absolutely nothing wrong with the Newtonsoft library. You can still persist with your method.
Try this:-
var json = JObject.Parse(returnStr);
var fields = (JArray)json["contacts"]["contact"][0]["fields"];
var givenName = fields[0]["value"]["givenName"];
var familyName = fields[0]["value"]["familyName"];
var email = fields[1]["value"];

Deserializing an array of different object types

Using the Json.NET library, I'm having trouble deserializing some json returned as an array. The json is an array containing some paging information as an object and array of country objects. Here's a sample of the returned json:
[
{
"page": 1,
"pages": 6,
"per_page": "50",
"total": 262
},
[
{
"id": "ABW",
"iso2Code": "AW",
"name": "Aruba",
"region": {
"id": "LCN",
"value": "Latin America & Caribbean (all income levels)"
},
"adminregion": {
"id": "",
"value": ""
},
"incomeLevel": {
"id": "NOC",
"value": "High income: nonOECD"
},
"lendingType": {
"id": "LNX",
"value": "Not classified"
},
"capitalCity": "Oranjestad",
"longitude": "-70.0167",
"latitude": "12.5167"
}
]
]
I am attempting to deserialize to the following types:
class CountriesQueryResults
{
public PagingInfo PageInfo { get; set; }
public List<CountryInfo> Countries { get; set; }
}
class PagingInfo
{
public int Page { get; set; }
public int Pages { get; set; }
[JsonProperty("per_page")]
public int ResultsPerPage { get; set; }
public int Total { get; set; }
}
class CountryInfo
{
public string Id { get; set; }
public string Iso2Code { get; set; }
public string Name { get; set; }
public string Longitude { get; set; }
public string Latitude { get; set; }
public string CapitalCity { get; set; }
public CompactIdentifier Region { get; set; }
public CompactIdentifier AdminRegion { get; set; }
public CompactIdentifier IncomeLevel { get; set; }
public CompactIdentifier LendingType { get; set; }
}
class CompactIdentifier
{
public string Id { get; set; }
public string Value { get; set; }
}
I am calling DeserializeObject as so:
var data = JsonConvert.DeserializeObject<List<CountriesQueryResults>>(response);
I am getting the following error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'CountriesQueryResults' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
I have been trying to get the answer from the documentation but I can't seem to figure it out. Any help would be appreciated.
Since your json is like this [ {....} , [{....}] ], You can only deserialize it to an object array(Where first item is an object and second, another array).
This simplest way I think to convert it to a c# object is:
var jArr = JArray.Parse(jsonstr);
var pageInfo = jArr[0].ToObject<PagingInfo>();
var countryInfos = jArr[1].ToObject<List<CountryInfo>>();
Class definitions would be:
public class PagingInfo
{
public int page { get; set; }
public int pages { get; set; }
[JsonProperty("per_page")]
public int ResultsPerPage { get; set; }
public int total { get; set; }
}
public class Region
{
public string id { get; set; }
public string value { get; set; }
}
public class AdminRegion
{
public string id { get; set; }
public string value { get; set; }
}
public class IncomeLevel
{
public string id { get; set; }
public string value { get; set; }
}
public class LendingType
{
public string id { get; set; }
public string value { get; set; }
}
public class CountryInfo
{
public string id { get; set; }
public string iso2Code { get; set; }
public string name { get; set; }
public Region region { get; set; }
public AdminRegion adminregion { get; set; }
public IncomeLevel incomeLevel { get; set; }
public LendingType lendingType { get; set; }
public string capitalCity { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
}
PS: You can change the property names' first char to Uppercase if you want. I used http://json2csharp.com/ to automatically generate those classes.

Categories

Resources