I've popped consuming a WebServer returning the Json bellow, and I'm not able to convert it to an object.
Json
{
"success":true,
"data":{
"24486146360":{
"rfid":"123465789456",
"products":[
{
"sale_id":35,
"quantity":2,
"price":"1",
"total":"2",
"unit":"uni",
"sku":14
},
{
"sale_id":36,
"quantity":2,
"price":"2.5",
"total":"5",
"unit":"uni",
"sku":17
}
]
},
"24758345953":{
"rfid":"2129",
"products":[
{
"sale_id":39,
"quantity":1,
"price":"10",
"total":"10",
"unit":"ml",
"sku":19998
}
]
},
"64577015900":{
"rfid":"1934",
"products":[
{
"sale_id":40,
"quantity":1,
"price":"10",
"total":"10",
"unit":"ml",
"sku":19998
}
]
},
"56768990934":{
"rfid":"1746",
"products":[
{
"sale_id":46,
"quantity":1,
"price":"8.00",
"total":"8",
"unit":"UN",
"sku":20
}
]
}
}
}
I used json2sharp to generate a class from the JSON, I then cleaned up the class and was left with the following:
My Class create help for json2sharp
public class Consumo
{
public string rfid { get; set; }
public List<ConsumoProduto> products { get; set; }
}
public class ConsumoProduto
{
public int sale_id { get; set; }
public double quantity { get; set; }
public string price { get; set; }
public string total { get; set; }
public string unit { get; set; }
public int sku { get; set; }
}
public class RetornoConsumo
{
[JsonProperty("success")]
public bool Processado { get; set; }
[JsonProperty("data")]
public List<Consumo> Registro { get; set; }
}
My Problem
how do I convert Json to a valid object using Json.Net?
Test
I tried to do this and I could not
Dictionary<string, RetornoConsumo> _featuredArticles = JsonConvert.DeserializeObject<Dictionary<string, RetornoConsumo>>(json);
In your RetornoConsumo class, the Registro property needs to be a Dictionary<string, Consumo> not a List<Consumo>.
public class RetornoConsumo
{
[JsonProperty("success")]
public bool Processado { get; set; }
[JsonProperty("data")]
public Dictionary<string, Consumo> Registro { get; set; }
}
Then, you need to deserialize the JSON into the RetornoConsumo class:
var data = JsonConvert.DeserializeObject<RetornoConsumo>(json);
Fiddle: https://dotnetfiddle.net/vfhdXp
Related
I know people asked and already got some answers very similar question before like this, but still, I couldn't figure it out about mine. I have a JSON file contains a multidimensional object, like below:
{
"Common": {
"Required": "Required Entry ",
"Photos": "Photos",
"Videos": "Videos",
"Register": "Register"
},
"Forms": {
"Form": "Forms",
"Name": "Name",
"Phone": "Phone",
"Email": "Email",
"Message": "Message"
},
"Sections": {
"Home": {
"EventDateTime": "",
"MainTitle": "",
"SubTitle": ""
},
"About": {},
"Venue": {},
"Schedule": {},
"Speakers": {},
"Sponsors": {},
"Price": {},
"Contact": {}
}
}
I would like to deserialize it into my view model (LanguagesViewModel) like this:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class LanguagesViewModel
{
public Common Common { get; set; }
public Buttons Buttons { get; set; }
public Forms Forms { get; set; }
public Navbar Navbar { get; set; }
public Sections Sections { get; set; }
}
public class Common
{
public string Required { get; set; }
public string Photos { get; set; }
public string Videos { get; set; }
public string Register { get; set; }
}
public class Forms
{
public string Form { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Message { get; set; }
}
public class Sections
{
public Home Home { get; set; }
public About About { get; set; }
public Venue Venue { get; set; }
public Schedule Schedule { get; set; }
public Speakers Speakers { get; set; }
public Sponsors Sponsors { get; set; }
public Price Price { get; set; }
public Contact Contact { get; set; }
}
public class Home
{
public string EventDateTime { get; set; }
public string MainTitle { get; set; }
public string SubTitle { get; set; }
}
public class About
{
}
public class Venue
{
}
public class Schedule
{
}
public class Speakers
{
}
public class Sponsors
{
}
public class Price
{
}
public class Contact
{
}
}
Some of the snippet to do this:
using (StreamReader sr = new StreamReader(language_file_path))
{
string contents = sr.ReadToEnd();
items = JsonConvert.DeserializeObject<LanguagesViewModel>(contents);
}
Somehow, I only can get the first level of the objects, which is:
LanguagesViewModel{
Common:null,
Forms:null,
Sections:null
}
Not the second level, not the third level. Did I do something wrong or have I missed something? Very appreciated for any kind of help.
Thank you.
You can Use this static class
public static class JsonHelper
{
public static T ToObject<T>(this string content)
{
var obj = JObject.Parse(content).GetValue(typeof(T).Name);
if (obj == null)
throw new NullReferenceException();
else
return obj.ToObject<T>();
//This ToObject here is default method written in object
}
}
Usage
var mymodel= json.ToObject<Forms>();
Or create a JSON object and read it with magic strings.
//Creating your JSON object
JObject content = JObject.Parse(sr.ReadToEnd()//or your json);
//content["your object name"] let you access to you object
var common =(Common)content["Common"];
in multidimensional objects, you can access them like this.
//content["level1"]["level2"]["level3"] & ...
var sections= (Home)content["Sections"]["Home"];
Also this way may work but i prefer the way with magic strings.
dynamic jsonObject = new JObject.Parse(sr.ReadToEnd());
var common = jsonObject.Common;
You can find more in this link
I hope this Helps!
I Get json data from third party in json format.
I am trying to fetch RollId from "Id" and MType from "Data" in some cases
"Data" doesn't have fields it is kind of blank.
It's working when we have "Data". In case of blank it's not working.
any idea on this? Is there a better approach of doing this?
This is the Json
string json = #"{
'root': {
'_type': '_container',
'Class': '.key.PModel',
'Elements': {
'_type': 'array<element>',
'_data': [
{
'_type': 'element',
'Class': '.key.PElement',
'Id': {
'_type': 'testId',
'Class': '.key.PModel',
'RollId': '.key.7157'
},
'Data': {
'_type': 'p_model',
'Class': '.key.Unsupported',
'MType': '.TestMType',
'Version': {
'_type': 'test__version',
'Class': '.key.TestVersion',
}
}
},
{
'_type': 'element',
'Class': '.key.PElement',
'Id': {
'_type': 'TestId',
'Class': '.key.PModel',
'RollId': '.key.11261'
},
'Data': '.ref.root.Elements.0.Data'
},
{
'_type': 'element',
'Class': '.key.PElement',
'Id': {
'_type': 'TestId',
'Class': '.key.PModel',
'RollId': '.key.7914'
},
'Data': '.ref.root.Elements.0.Data'
}
]
}
}
}";
This is the Code
public class Program
{
static void Main(string[] args)
{
//it provide json
var testCont = thirdpartyapi();
var dataList = new List<TestResponse>();
foreach (var testData in testCont.Elements())
{
var data = new TestResponse();
data.col1 = Convert.ToInt32(testData.Id().RollId());
data.col2 = testData.Data().MType().ToString();
dataList.Add(data);
}
}
public class TestResponse
{
public int col1 { get; set; }
public string col2 { get; set; }
}
}
First, try to get a valid well-formed json. You can use this code beautify tool. Then you can automatically generate C# class using json2csharp. Finally as you have C# class you can apply if statements and check if property is null.
Generated C# wrapper:
public class Id
{
public string _type { get; set; }
public string Class { get; set; }
public string RollId { get; set; }
}
public class Datum
{
public string _type { get; set; }
public string Class { get; set; }
public Id Id { get; set; }
public object Data { get; set; }
}
public class Elements
{
public string _type { get; set; }
public List<Datum> _data { get; set; }
}
public class Root
{
public string _type { get; set; }
public string Class { get; set; }
public Elements Elements { get; set; }
}
public class RootObject
{
public int encoding_version { get; set; }
public Root root { get; set; }
}
If you want to pick only few fields from complex JSON, you can consider using Cinchoo ETL - an open source library
Sample below shows how to pick RollId and MType values from your json
using (var r = new ChoJSONReader("## YOUR JSON FILE PATH ##")
.WithJSONPath("$.._data")
.WithField("RollId", jsonPath: "$..Id.RollId", fieldType: typeof(string))
.WithField("MType", jsonPath: "$..Data.MType", fieldType: typeof(string))
)
{
foreach (var rec in r)
{
Console.WriteLine((string)rec.RollId);
Console.WriteLine((string)rec.MType);
}
}
Hope it helps.
The easiest way is use the DataContractJsonSerializer
Here you can read more about it.
All in all you need to create a model which has the same possible outcome as your json.
Then you can just use the DataContractJsonSerializer to create an object of you model by using a MemoryStream.
Here you can find a nice tool to create the model from the JSON.
For example this one:
public class Id
{
public string _type { get; set; }
public string Class { get; set; }
public string RollId { get; set; }
}
public class Datum
{
public string _type { get; set; }
public string Class { get; set; }
public Id Id { get; set; }
public object Data { get; set; }
}
public class Elements
{
public string _type { get; set; }
public List<Datum> _data { get; set; }
}
public class Root
{
public string _type { get; set; }
public string Class { get; set; }
public Elements Elements { get; set; }
}
public class RootObject
{
public int encoding_version { get; set; }
public Root root { get; set; }
}
Then you use the MemoryStream and the DataContractJsonSerializer to Create an object of RootObject from that JSON.
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));
stream1.Position = 0;
RootObject rootObject = (RootObject)ser.ReadObject(stream1);
And yes, as Adriani6 mentiones - your JSON is invalid at this point:
"Data": {
"_type": "p_model",
"Class": ".key.Unsupported",
"MType": ".TestMType",
"Version": {
"_type": "test__version",
"Class": ".key.TestVersion",
}
There is a , at the end wich is not allowed.
I am working with opentdb.com api and have no idea how to access data in this json:
{
"response_code":0,
"results": [
{
"category":"Animals",
"type":"multiple",
"difficulty":"easy",
"question":"What is the scientific name for modern day humans?",
"correct_answer":"Homo Sapiens",
"incorrect_answers":[
"Homo Ergaster",
"Homo Erectus",
"Homo Neanderthalensis"
]
},
{
"category":"Entertainment: Cartoon & Animations",
"type":"multiple",
"difficulty":"easy",
"question":"Who voices for Ruby in the animated series RWBY?",
"correct_answer":"Lindsay Jones",
"incorrect_answers":[
"Tara Strong",
"Jessica Nigri",
"Hayden Panettiere"
]
}
]
}
I am using Newtonsoft.Json and i tried this with only 1 Question but im geting an error that says that key value is wrong..
class Trivia
{
public Trivia(string json)
{
JObject jObject = JObject.Parse(json);
JToken jresults = jObject["results"];
category = (string)jresults["category"];
type = (string)jresults["type"];
difficulty = (string)jresults["difficulty"];
question = (string)jresults["question"];
correct_answer = (string)jresults["correct_answer"];
incorrect_answers = jresults["incorrect_answers"].ToArray();
}
public string category { get; set; }
public string type { get; set; }
public string difficulty { get; set; }
public string question { get; set; }
public string correct_answer { get; set; }
public Array incorrect_answers { get; set; }
}
Copy from json text and in new class in visual studio Edit-->Paste Special-->Paste JSON As Classes
public class Rootobject
{
public int response_code { get; set; }
public Result[] results { get; set; }
}
public class Result
{
public string category { get; set; }
public string type { get; set; }
public string difficulty { get; set; }
public string question { get; set; }
public string correct_answer { get; set; }
public string[] incorrect_answers { get; set; }
}
using namespace
using Newtonsoft.Json;
response is value get from your service
var outdeserialized = JsonConvert.DeserializeObject<Rootobject>(response);
I am receiving the json response of below format from an api. I am trying to deserialze it with custom class.
{
"TraceEvent": {
"Attributes": {
"Commodity": "APPLES",
"Variety": "Green"
},
"Codes": [{
"devicename": "",
"code": "901491877572115",
"timestamp": "2018-02-15T19:33:29.4418926+05:30"
}, {
"devicename": "",
"code": "6657287134488755",
"timestamp": "2018-02-15T19:33:29.4418926+05:30"
}
]
}
}
Below is my custom class used for deserialize
public class EventContainer
{
[JsonProperty("TraceEvent")]
public TraceEvent TraceEvent { get; set; }
}
public class TraceEvent
{
[JsonProperty("attributes")]
public TraceAttributes Attributes { get; set; }
[JsonProperty("codes")]
public TraceCodes Codes { get; set; }
}
public class TraceAttributes
{
[JsonProperty("commodity")]
public string Commodity { get; set; }
[JsonProperty("variety")]
public string Variety { get; set; }
}
public class TraceCodes
{
public TraceCodes()
{
Codes = new List<TraceCode>();
}
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}
public class TraceCode
{
[JsonProperty("devicename")]
public string DeviceName { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("timestamp")]
public DateTime Timestamp { get; set; }
}
In the receiver side, i am getting null for the Codes. Plesae refer my debug screen in api receiver code,
Can any one tell me how to rewrite my custom class to deserialize the Codes list from JSON api
Thanks for the help.
Change the class structure. The Codes should be in TraceEvent class not in its own class
public class TraceEvent
{
[JsonProperty("attributes")]
public TraceAttributes Attributes { get; set; }
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}
Remove below class
public class TraceCodes
{
public TraceCodes()
{
Codes = new List<TraceCode>();
}
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}
TraceEvent has a property
public TraceCodes Codes { get; set; }
And TraceCodes is another object with a list of codes:
public List<TraceCode> Codes { get; set; }
This would mean there would have to be a structure like this:
{
"TraceEvent": {
"Codes": {
"Codes": [
{ … },
{ … },
}
}
}
}
So the "Codes" part is double. Instead, you need to modify your TraceEvent to have that list directly:
public class TraceEvent
{
[JsonProperty("attributes")]
public TraceAttributes Attributes { get; set; }
[JsonProperty("Codes")]
public List<TraceCode> Codes { get; set; }
}
Btw. that should have actually resulted in a JsonSerializationException, so you should check whether that gets swallowed somewhere.
I use JSON.NET and I would like to parse the following object which I get from a WebService. Can someone post an example on how to do that?
#"{""MessageType"":0,
""Message"":""Success"",
""Value"":[
{""listId"":1,
""listName"":""DemoList"",
""itemInList"":[
{
""fromDate"":""\/Date(1228946400000)\/"",
""fromLocation"":null,
""toLocation"":null,
""originalRequest"":""water"",
""creationDate"":""\/Date(1339448400000)\/"",
""typeId"":1
},
{
""fromDate"":null,
""fromLocation"":null,
""toLocation"":null,
""originalRequest"":""gala"",
""creationDate"":""\/Date(1304370000000)\/"",
""typeId"":1
}
]}
]}"
JSON Object
{
"MessageType":0,
"Message":"UserLists",
"Value":
[
{
"listId":1,
"listName":"DemoList",
"itemInList"
[
{
"fromDate":"\/Date(1228946400000)\/",
"fromLocation":null,
"toLocation":null,
"originalRequest":"water",
"creationDate":"\/Date(1339448400000)\/",
"typeId":1
},
{
"fromDate":null,
"fromLocation":null,
"toLocation":null,
"originalRequest":"gala",
"creationDate":"\/Date(1304370000000)\/",
"typeId":1
}
],
"numberOfItems":2
}
]
}
Thanks.
You need to create some entity like this:
public class Entity
{
public int MessageType { get; set; }
public string Message { get; set; }
public List<EntityValue> Value { get; set; }
}
public class EntityValue
{
public int listId { get; set; }
public string listName { get; set; }
public List<ItemInList> itemInList { get; set; }
}
public class ItemInList
{
public DateTime? fromDate { get; set; }
public string fromLocation { get; set; }
public string toLocation { get; set; }
public string originalRequest { get; set; }
public DateTime creationDate { get; set; }
public int typeId { get; set; }
}
The entity must has the same structure like the json data.
And you can call the Method:
JsonConvert.DeserializeObject<Entity>(json);
If it has any exception,you need to adjust the entities until it works.
Please read the below link for parsi in metro style application.
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh770287.aspx