No results from Json Deserialize - c#

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.

Related

Deserialize Json string with child objects

Got the following structure given:
public class TaskList
{
public string Name { get; set; }
public List<ToDoTask> ToDoTasks { get; set; }
}
public class ToDoTask
{
public string Name { get; set; }
public string Note { get; set; }
public DateTime LastEdit { get; set; }
public bool Finished { get; set; }
}
I'm using System.Text.Json in .NET 5.0 to serialize a List successfully into a json-file:
JsonSerializerOptions serializeOptions = new() { WriteIndented = true };
string json = JsonSerializer.Serialize(taskLists, serializeOptions);
the result looks fine:
{
"TaskLists": [
{
"Name": "List1",
"ToDoTasks": [
{
"Name": "Task1",
"Note": "",
"LastEdit": "2022-04-19T13:05:10.0415588+02:00",
"Finished": false
},
{
"Name": "Task2",
"Note": "",
"LastEdit": "2022-04-19T13:05:13.9269202+02:00",
"Finished": false
}
]
},
{
"Name": "List2",
"ToDoTasks": [
{
"Name": "Task3",
"Note": "",
"LastEdit": "2022-04-19T13:05:18.3989081+02:00",
"Finished": false
},
{
"Name": "Task4",
"Note": "",
"LastEdit": "2022-04-19T13:05:23.0949034+02:00",
"Finished": false
}
]
}
]
}
When I deserialize this json-file, I only got the TaskLists but the ToDoTasks, are empty.
List<TaskList> taskLists = JsonSerializer.Deserialize<List<TaskList>>(json);
What do I have to do, get also the ToDoTask-Childs included into the deserialized objects?
Whenever you cannot figure out your model class, you can use Visual Studio's Edit - Paste Special - Paste JSON as Class to check out.
Your model classes should be like this:
public class Rootobject
{
public Tasklist[] TaskLists { get; set; }
}
public class Tasklist
{
public string Name { get; set; }
public Todotask[] ToDoTasks { get; set; }
}
public class Todotask
{
public string Name { get; set; }
public string Note { get; set; }
public DateTime LastEdit { get; set; }
public bool Finished { get; set; }
}
And you can Deserialize it:
static void Main(string[] args)
{
var query = JsonSerializer.Deserialize<Rootobject>(File.ReadAllText("data.json"));
}
Your json has a root object containing the task list, so List<TaskList> does not represent it correctly. Try:
public class Root
{
public List<TaskList> TaskLists { get; set; }
}
var root = JsonSerializer.Deserialize<Root>(json);

Deserialize JSON in xamarin

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

Deserializing JSON with numbers as key

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

json.net deserialization return null

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"
}
}
]
}

What is the correct class structure in C# to convert this Json into?

I have the following Json below coming from a Rest service and I am trying to deserialize it into a C# object using this code:
var _deserializer = new JsonDeserializer();
var results = _deserializer.Deserialize<Report>(restResponse);
The deserialize method keeps returning null which tells me that my C# object is not structured correctly.
Below is the Json and my latest attempt at the C# definition.
{
"Report": [
{
"ID": "0000014",
"Age": "45",
"Details": [
{
"Status": "Approved",
"Name": "Joe"
},
{
"Status": "Approved",
"Name": "Bill"
},
{
"Status": "Submitted",
"Name": "Scott"
}
]
},
{
"ID": "10190476",
"Age": "40",
"Details": [
{
"Status": "Approved",
"Name": "Scott"
}
]
},
{
"ID": "10217480",
"Age": "40",
"Details": [
{
"Status": "Approved",
"Name": "Scott"
}
]
}
]
}
Here is my C# object:
public class Report
{
public List<WorkItem> Item= new List<WorkItem>();
}
public class WorkItem
{
public string ID { get; set; }
public int Age { get; set; }
public List<Details> Details { get; set; }
}
public class Details
{
public string Status { get; set; }
public string Name { get; set; }
}
Can someone advise what is wrong with my C# object definition to make this json deserialize correctly?
I would recommend using Json2Csharp.com to generate the classes.
public class Detail
{
public string Status { get; set; }
public string Name { get; set; }
}
public class Report
{
public string ID { get; set; }
public string Age { get; set; }
public List<Detail> Details { get; set; }
}
public class RootObject
{
public List<Report> Report { get; set; }
}
Try changing the Report class like so (The class name can be anything, the property must be Report)
public class WorkReport
{
public List<WorkItem> Report;
}
It should be trying to deserialize at the root into a class with an array/list of of workitem objects called Report.
You can try something like this. I have changed List to Dictionary You don't have a class defined at the root level. The class structure needs to match the entire JSON, you can't just deserialize from the middle. Whenever you have an object whose keys can change, you need to use a Dictionary. A regular class won't work for that; neither will a List.
public class RootObject
{
[JsonProperty("Report")]
public Report Reports { get; set; }
}
public class Report
{
[JsonProperty("Report")]
public Dictionary<WorkItem> Item;
}
public class WorkItem
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("Age")]
public int Age { get; set; }
[JsonProperty("Details")]
public Dictionary<Details> Details { get; set; }
}
public class Details
{
[JsonProperty("Status")]
public string Status { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
}
Then, deserialize like this:
Report results = _deserializer.Deserialize<Report>(restResponse);

Categories

Resources