I'm trying to deserialize a JSON string into a C# object. When I trap in the debugger, the JSON visualizer appears to be parsing the string just fine. However, when I push the string through the following code, the object returned has null values for the properties.
Here's my code:
public static Item GetPrices(string itemStr)
{
Item item = JsonConvert.DeserializeObject<Item>(itemStr);
return item;
}
public class Item
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "prices")]
public Prices Prices { get; set; }
}
public class Prices
{
[JsonProperty(PropertyName = "priceUofM")]
public PriceUofM[] PriceUofMs { get; set; }
}
public class PriceUofM
{
[JsonProperty(PropertyName = "uofm")]
public string UofM { get; set; }
[JsonProperty(PropertyName = "price")]
public string Price { get; set; }
}
and here's what I'm passing to it:
{
"item": {
"id": "1A50CC070S",
"prices":
[
{
"priceUofM": {
"uofm": "BOX",
"price": "$81.11"
}
},
{
"priceUofM": {
"uofm": "CASE",
"price": "$811.11"
}
}
]
}
}
I've run it through several online parsers, and all of them appear to be interpreting the JSON string just fine. What am I doing wrong in formatting the string to cause JsonConvert.DeserializeObject to fail?
Given this json:
{
"item": {
"id": "1A50CC070S",
"prices":
[
{
"priceUofM": {
"uofm": "BOX",
"price": "$81.11"
}
},
{
"priceUofM": {
"uofm": "CASE",
"price": "$811.11"
}
}
]
}
}
C# model would be:
public class Model
{
[JsonProperty("item")]
public Item Item { get; set; }
}
public class Item
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("prices")]
public List<Price> Prices { get; set; }
}
public class Price
{
[JsonProperty("priceUofM")]
public PriceUofM PriceUofM { get; set; }
}
public class PriceUofM
{
[JsonProperty("uofm")]
public string UofM { get; set; }
[JsonProperty("price")]
public string Price { get; set; }
}
In order to deserialize the string into an Item object, JSON string would be something like:
{
"id": "1A50CC070S",
"prices":
[
{
"priceUofM": {
"uofm": "BOX",
"price": "$81.11"
}
},
{
"priceUofM": {
"uofm": "CASE",
"price": "$811.11"
}
}
]
}
Related
How can i deserialize a local json file to an object?
I'm trying to deserialize a local json file in xamarin but it just doesn't work i read many guides and watched some tutorials but none of them helped and most of them give the same code i'm using right now
My code:
public test()
{
InitializeComponent();
List<Rootobject> ob = new List<Rootobject>();
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(test)).Assembly;
Stream stream = assembly.GetManifestResourceStream($"TunisiaPrayer.states.json");
string text = "";
using (var reader = new StreamReader(stream))
{
text = reader.ReadToEnd();
}
ob = JsonConvert.DeserializeObject<List<Rootobject>>(text);
//printing the json file to make sure it read it fully
//i get no error here
DisplayJson.Text = text;
//try catch to test if it was deserialized or not
try
{
//printing a property of ob in a label element to see if it works
DisplayData.Text = ob[2].Property1.data.gouvernorat.intituleAn;
}
catch (Exception ex)
{
DisplayData.Text = ex.Message;
}
}
RootObject Class:
namespace TunisiaPrayer.Models
{
public class Rootobject
{
public Class1 Property1 { get; set; }
}
public class Class1
{
public Data data { get; set; }
}
public class Data
{
public Gouvernorat gouvernorat { get; set; }
public Delegation[] delegation { get; set; }
}
public class Gouvernorat
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}
public class Delegation
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}
}
sample of states.json:
[{
"data": {
"gouvernorat": {
"id": 358,
"intituleAr": "اريانة",
"intituleAn": "Ariana"
},
"delegation": [{
"id": 631,
"intituleAr": "اريانة",
"intituleAn": "Ariana"
},
{
"id": 534,
"intituleAr": "التظامن",
"intituleAn": "Attadhamon"
},
{
"id": 532,
"intituleAr": "سكرة",
"intituleAn": "Soukra"
}
]
}
},
{
"data": {
"gouvernorat": {
"id": 362,
"intituleAr": "القصرين",
"intituleAn": "Kasserine"
},
"delegation": [{
"id": 579,
"intituleAr": "العيون",
"intituleAn": "El Ayoun"
},
{
"id": 576,
"intituleAr": "سبيبة",
"intituleAn": "Sbiba"
},
{
"id": 575,
"intituleAr": "سبيطلة",
"intituleAn": "Sbitla"
},
{
"id": 573,
"intituleAr": "تالة",
"intituleAn": "Tala"
}
]
}
}]
error: Object reference not set to an instance of an object
note that when i print ob.Count it gives me the correct length of the list but i can't access any data in it
you have to use Root[] , not just root, try this
var obj =JsonConvert.DeserializeObject< List<Root>>(text);
test
var displayData = obj[1].data.gouvernorat.intituleAn; // = Kasserine
classes
public class Root
{
public Data data { get; set; }
}
public class Data
{
public Gouvernorat gouvernorat { get; set; }
public List<Delegation> delegation { get; set; }
}
public class Gouvernorat
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}
public class Delegation
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}
I have JSON like this:
{
"success": 1,
"method": "getTrades",
"5183": {
"buy_amount": "0.00455636",
"buy_currency": "BTC"
},
"6962": {
"buy_amount": "52.44700000",
"buy_currency": "IOT"
},
"6963": {
"buy_amount": "383.54300000",
"buy_currency": "TNT"
},
"6964": {
"buy_amount": "3412.50000000",
"buy_currency": "FUN"
},
"6965": {
"buy_amount": "539.45000000",
"buy_currency": "XLM"
}
}
I need to convert this JSON to domain model.
public class Root {
[JsonProperty("success")]
public long Success { get; set; }
[JsonProperty("method")]
public string Method { get; set; }
public Dictionary<long, Transaction> Transactions { get; set; }
public class Transaction{
[JsonProperty("buy_amount")]
public decimal? BuyAmount { get; set; }
[JsonProperty("buy_currency")]
public string BuyCurrency { get; set; }
var model = JsonConvert.DeserializeObject<Root>(response);
I created these two models, but when I try to deserialize transactions, they are null. I got data for success and method
Either the json needs to change, or you need to modify your c# structures. Not 100% sure, but based on the JSON, the c# class should be
public class Root : Dictionary<long, Transaction> {
[JsonProperty("success")]
public long Success { get; set; }
[JsonProperty("method")]
public string Method { get; set; }
Can you change the JSON to something like this?
{
"success": 1,
"method": "getTrades",
"transaction": [
{
"id": 5183,
"buy_amount": "0.00455636",
"buy_currency": "BTC"
},
{
"id": 6962,
"buy_amount": "52.44700000",
"buy_currency": "IOT"
},
{
"id": 6963,
"buy_amount": "383.54300000",
"buy_currency": "TNT"
},
{
"id": 6964,
"buy_amount": "3412.50000000",
"buy_currency": "FUN"
},
{
"id": 6965,
"buy_amount": "539.45000000",
"buy_currency": "XLM"
}
]
}
Then you could do something like that:
public class Transaction {
public int id { get; set; }
public string buy_amount { get; set; }
public string buy_currency { get; set; }
}
public class Root {
public int success { get; set; }
public string method { get; set; }
public List<Transaction> transaction { get; set; }
}
I deserialaize my json to a model class fine but i want to do some work on the boxes array before saving to sqlite, I'm stuck on looping through all the boxes and get the values.
{
"data": [ // single outer array
{
"id": 8620379,
"business_id": 191,
"business_name": "yada",
"boxes": [
{
"box_id": 485,
"box_name": "5/6",
"box_group": null
},
{
"box_id": 483,
"box_name": "1/2",
"box_group": null
},
{
"box_id": 484,
"box_name": "3/4",
"box_group": null
}
]
},
{
"id": 8636759,
"business_id": 257,
"business_name": "something else",
"boxes": [
{
"box_id": 1176,
"box_name": "FC",
"box_group": null
}
]
}, // and more boxes
Create a model for the JSON object. (http://json2csharp.com/)
public class Box
{
public int box_id { get; set; }
public string box_name { get; set; }
public object box_group { get; set; }
}
public class Datum
{
public int id { get; set; }
public int business_id { get; set; }
public string business_name { get; set; }
public List<Box> boxes { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
Using Json.NET JSON deserializer,
RootObject obj = JsonConvert.DeserializeObject<RootObject>("your json string");
I am getting the json from zoho. I have a JSON like the following:
{
"response": {
"result": {
"Leads": {
"row": [
{
"no": "1",
"FL": [
{
"content": "1325469000000679001",
"val": "LEADID"
},
{
"content": "1325469000000075001",
"val": "SMOWNERID"
},
{
"content": "Geoff",
"val": "Lead Owner"
},
]
},
{
"no": "2",
"FL": [
{
"content": "1325469000000659017",
"val": "LEADID"
},
{
"content": "1325469000000075001",
"val": "SMOWNERID"
},
{
"content": "Geoff",
"val": "Lead Owner"
},
]
},
]
}
},
"uri": "/crm/private/json/Leads/getRecords"
}
}
I am using the following classes:
public class Row
{
[JsonProperty(PropertyName = "row")]
public List<Leads> row { get; set; }
}
public class Leads
{
[JsonProperty(PropertyName = "no")]
public string nbr { get; set; }
[JsonProperty(PropertyName = "FL")]
public List<Lead> FieldValues { get; set; }
}
public class Lead
{
[JsonProperty(PropertyName = "content")]
public string Content { get; set; }
[JsonProperty(PropertyName = "val")]
public string Val { get; set; }
}
I try to deserialize the json and get back nothing:
var mList = JsonConvert.DeserializeObject<IDictionary<string, Row>>(result);
This is the first time working with Json so any help would be appreciated!
Usually when that happens it is because your class model for deserialization is wrong. Rather than trying to hand-craft the classes I like to use http://json2csharp.com. Just plug in your JSON and it gives you the necessary C# classes. In your case it provides the following.
public class FL
{
public string content { get; set; }
public string val { get; set; }
}
public class Row
{
public string no { get; set; }
public List<FL> FL { get; set; }
}
public class Leads
{
public List<Row> row { get; set; }
}
public class Result
{
public Leads Leads { get; set; }
}
public class Response
{
public Result result { get; set; }
public string uri { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
You can then deserialize into RootObject using:
var mList = JsonConvert.DeserializeObject<RootObject>(result);
Feel free to rename RootObject to whatever name you like better.
The problem is, I receive a list of posts from facebook (page feed) which occasionally holds multiple comments in an array inside the post object. Only the first comment of the post gets parsed correctly. Somehow the second and later comments don't get parsed.
This is the JSON I'm going on about:
{
"data": [ //Root object
{ //Post object
"id": "153411918116843_304953306296036",
"from": {
"category": "Sports/recreation/activities",
"category_list": [
{
"id": "124887510918208",
"name": "Swimming Pool"
}
],
"name": "Twentebad",
"id": "153411918116843"
},
"link": "http://dlvr.it/5bBKPx",
"picture": "irrelevant",
"message": "Onderzoek renovatie Twentebad! http://dlvr.it/5bBKPx",
"created_time": "2014-05-07T09:44:18+0000",
"comments": { // Collective comments object
// Actual comments objects in array !!!!! ONLY FIRST GETS PARSED !!!!
"data": [
{ //Comment object
"id": "304953306296036_304959069628793",
"from": {
"id": "884483928243965",
"name": "Selena Suzan Valentino"
},
"message": "Twentepalace",
"can_remove": false,
"created_time": "2014-05-07T10:32:26+0000",
"like_count": 0,
"user_likes": false
},
{ Unparsed comment object
"id": "304953306296036_305126702945363",
"from": {
"id": "884483928243965",
"name": "Selena Suzan Valentino"
},
"message": "Na baantjes trekken vooral heerlijk...",
"can_remove": false,
"created_time": "2014-05-08T09:12:43+0000",
"like_count": 0,
"user_likes": false
},
{ //Unparsed comment object
"id": "304953306296036_305126622945371",
"from": {
"id": "884483928243965",
"name": "Selena Suzan Valentino"
},
"message": "Wil infrarood sauna weer terug komt...",
"can_remove": false,
"created_time": "2014-05-08T09:11:20+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "MQ==",
"before": "Mw=="
}
},
"summary": {
"order": "ranked",
"total_count": 3
}
}
}
]
}
I'm using JSON.NET to parse this json to a typed object list like this:
foreach (JToken facebookItem in data["data"])
{
JToken messageCheck = facebookItem.SelectToken("message", false); //Irrelevante post als er geen inhoud in zit (false = geen error melding indien null)
if (messageCheck != null)
{
itemsToAdd.Add(facebookItem.ToObject<FacebookItem>());
}
}
The FacebookItem class looks like this:
public class FacebookItem
{
public string id { get; set; }
public From from { get; set; }
public string link { get; set; }
public string picture { get; set; }
public string message { get; set; }
public string created_time { get; set; }
public Comments comments { get; set; }
public PostPaging paging { get; set; }
public class PostCategories
{
public string id { get; set; }
public string name { get; set; }
}
public class From
{
public string category { get; set; }
public List<PostCategories> category_list { get; set; }
public string name { get; set; }
public string id { get; set; }
}
public class CommentCategories
{
public string id { get; set; }
public string name { get; set; }
}
//Root of Comments ("data":[ "comments":{ [],{},{} } ])
public class Comments
{
public List<CommentData> data { get; set; } //SHOULD HOLD MORE THAN 1
public CommentPaging paging { get; set; }
public Summary summary { get; set; }
}
//Data gegevens van comments ("data":[ "comments":{ "data":[],{},{} } ])
public class CommentData
{
public string id { get; set; }
public CommentFrom from { get; set; }
public string message { get; set; }
public bool can_remove { get; set; }
public string created_time { get; set; }
public int like_count { get; set; }
public bool user_likes { get; set; }
}
//Data gegevens van ccommenter ("data":[ "comments":{ "data":[ "from":{} ],{},{} } ])
public class CommentFrom
{
public string id { get; set; }
public string name { get; set; }
public string category { get; set; }
public List<CommentCategories> category_list { get; set; }
}
//Paging gegevens van comments ("data":[ "comments":{ [],"paging":{},{} } ])
public class CommentPaging
{
public Cursors cursors { get; set; }
}
//Summary gegevens van comments ("data":[ "comments":{ [],{},"summary":{} } ])
public class Summary
{
public string order { get; set; }
public int total_count { get; set; }
}
public class Cursors
{
public string after { get; set; }
public string before { get; set; }
}
public class PostPaging
{
public string previous { get; set; }
public string next { get; set; }
}
}
Is there a Json.net expert out there that undertands why only the first comment gets parsed?
This is what the debugger show me:
I'll tell you where I live, please come and kill me...
I called the url from localstorage. I changed the url but changes aren't detected so it doesn't get overwritten.
So, why only one comment? I had the comments' limit set to 1 :(
Not as exiting as I hoped this would be.
Hopefully the info provided can help someone in the future.