deserialize the following json response in c# - c#

Can someone please help me deserialize the following JSON string in C#:
{"legend_size": 1,
"data": {"series": ["2013-02-05", "2013-02-06", "2013-02-07", "2013-02-08", "2013-02-09", "2013-02-10", "2013-02-11", "2013-02-12", "2013-02-13", "2013-02-14"], "values":
{"CampaignHit": {"2013-02-14": 0, "2013-02-13": 0, "2013-02-12": 0, "2013-02-11": 0, "2013-02-10": 0, "2013-02-08": 11, "2013-02-05": 0, "2013-02-07": 14, "2013-02-06": 0, "2013-02-09": 0}}}}
I having problems with the CampaignHit part. I am not able to deserialize it.
Here are the classes I created:
public class ExportedData
{
public string legend_size { get; set; }
public Data data { get; set; }
}
public class Data
{
public string[] series { get; set; }
public Values values { get; set; }
}
public class Values
{
public CampaignHit CampaignHit { get; set; }
}
public class CampaignHit
{
public CampaignData[] data { get; set; }
}
public class CampaignData
{
public object first { get; set; }
public object second { get; set; }
}
Here is the code to deserialize json:
var result = JsonConvert.DeserializeObject<ExportedData>(jsonResponse);
The data part is null. How do I change the CampaignHit class so that data is not null after deserialization.

A solution using Newtonsoft.Json :
JObject jObject = JObject.Parse(#"{
'legend_size': 1,
'data': {
'series': [
'2013-02-05', '2013-02-06', '2013-02-07', '2013-02-08', '2013-02-09', '2013-02-10', '2013-02-11', '2013-02-12', '2013-02-13', '2013-02-14'
],
'values': {
'CampaignHit': {
'2013-02-14': 0,
'2013-02-13': 0,
'2013-02-12': 0,
'2013-02-11': 0,
'2013-02-10': 0,
'2013-02-08': 11,
'2013-02-05': 0,
'2013-02-07': 14,
'2013-02-06': 0,
'2013-02-09': 0
}
}
}
}");
var campaignHit = jObject["data"]["values"]["CampaignHit"];
Dictionary<string,int> campaignHitDic = new Dictionary<string,int>();
foreach(JProperty c in campaignHit){
campaignHitDic.Add(c.Name,(int)c.Value);
}

Related

Desalinizing JSON Object Contains List of Objects Returns Null for the nested object

This is my first attempt of working with JSON deserialization. I have read many of the posts in Stackoverflow, non of the suggested solutions could match my issue, so my apology in advance. I have created the following objects:
public class Item
{
public int ID { get; set; }
public int LSum { get; set; }
public int YSum { get; set; }
public int TSum { get; set; }
public int NSum { get; set; }
public int MemberId { get; set; }
}
public class Something
{
public int Id { get; set; }
public string Phone { get; set; }
public bool ExistingMember { get; set; }
public IList<Item> Item { get; set; }
}
And when deserialize the JSON it looks like following:
The follwoing JSON what I expect it to be:
{
"Id":62,
"Phone":"07",
"ExistingMember":true,
"Item":[
{
"ID":42,
"LSum":0,
"YSum":0,
"TSum":0,
"NSum":0,
"MemberId":12
}
]
}
However the following method it
some= JsonConvert.DeserializeObject<something>(someResponse);
It prints the json like the following:
The following JSON is what is "someResponse" return,
{
"Id":62,
"Phone":"07",
"ExistingMember":true,
"Item":null
}
What am I missing that the item list is return null?
If you want to deserialize json string which in your case is someResponse variable, then you are doing it right.
To check your code I created a JSON file with a file.json name and put the following on it:
{
"Id": 62,
"Phone": "07",
"ExistingMember": true,
"Item": [
{
"ID": 42,
"LSum": 0,
"YSum": 0,
"TSum": 0,
"NSum": 0,
"MemberId": 12
}
]
}
Then below lines of code take the content of JSON file (which in your case is the content of someResponse) and deserialize it into c# object of Something type:
string jsonFilePath = #"C:\test\file.json";
var some = JsonConvert.DeserializeObject<Something>(File.ReadAllText(jsonFilePath));
Then print the ID property of each element of Item list:
foreach(var item in some.Item)
{
if (item != null)
{
Console.WriteLine($"item ID = {item.ID}");
}
}
The output:
item ID = 42
So, it is quite possible that someResponse just does not have an Item and looks like this:
{
"Id": 62,
"Phone": "07",
"ExistingMember": true
}
UPDATE:
Also I tried like this:
var someResponse = #"{
'Id': 62,
'Phone': '07',
'ExistingMember': true,
'Item':[
{
'ID': 42,
'LSum': 0,
'YSum': 0,
'TSum': 0,
'NSum': 0,
'MemberId': 12
}
]
}
";
var some = JsonConvert.DeserializeObject<Something>(someResponse);
And some has a Item list with 1 element

Defining a dictionary in a C# class

I have a .json file which i want to read in C#.
The Json File looks like this:
{"SN0124":{
"category1": 0,
"output": {
"ABC": [],
"DEF": 0,
"GHI": "ABDEF"
},
"category2": 0,
"category3": 0
},
"SN0123":{
"category1": 0,
"output": {
"ABC": ["N1", "N2"],
"DEF": 0,
"GHI": "ABDEF"
},
"category2": 0,
"category3": 0
}
Initially the output field was absent and my custom class for reading the Json file is as follows:
namespace Server.Models
{
public class Pets
{
public string category1 { get; set; }
public string category2 { get; set; }
public string category3 { get; set; }
}
}
The output was recently added and I am not sure how to include that dictionary in the class file so that I can read the json file. Any help will be greatly appreciated.
thanks!
This should work fine. I have basically created a new class called Output that contains the expected JSON fields. I have also edited the type of the category fields to int.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string JSONInput = #"{""SN0124"": {
""category1"": 0,
""output"": {
""ABC"": [],
""DEF"": 0,
""GHI"": ""ABDEF""
},
""category2"": 0,
""category3"": 0
},
""SN0123"": {
""category1"": 0,
""output"": {
""ABC"": [""N1"", ""N2""],
""DEF"": 0,
""GHI"": ""ABDEF""
},
""category2"": 0,
""category3"": 0
}}";
Dictionary<string, Pets> deserializedProduct = JsonConvert.DeserializeObject<Dictionary<string, Pets>>(JSONInput);
Console.ReadKey();
}
}
public class Output
{
public string[] ABC { get; set; }
public int DEF { get; set; }
public string GHI { get; set; }
}
public class Pets
{
public int category1 { get; set; }
public Output output { get; set; }
public int category2 { get; set; }
public int category3 { get; set; }
}
}
I'm not sure I fully understand what you mean. If I understand right you're trying to hold the values from output in a dictionary?
You could do something like:
var output = new Dictionary<string, string[]>();
But it might be simpler to create a custom class to hold that data structures.

How can I deserialize my JSON string?

I have a serialized JSON string
string json = " [
{
\"id\": 1,
\"barcode\": \"TestBARCODE\",
\"nsr\": 0,
\"stk_in\": 0,
\"stk_out\": 0,
\"sales\": 0,
\"balance\": 1
},
{
\"id\": 2,
\"barcode\": \"TestBARCODE2\",
\"nsr\": 0,
\"stk_in\": 0,
\"stk_out\": 0,
\"sales\": 0,
\"balance\": 1
},
{
\"id\": 3,
\"barcode\": \"TestBARCODE3\",
\"nsr\": 0,
\"stk_in\": 0,
\"stk_out\": 0,
\"sales\": 0,
\"balance\": 1
},
{
\"id\": 4,
\"barcode\": \"AAA\",
\"nsr\": 0,
\"stk_in\": 0,
\"stk_out\": 0,
\"sales\": 0,
\"balance\": 1
},
{
\"id\": 5,
\"barcode\": \"BBB\",
\"nsr\": 0,
\"stk_in\": 0,
\"stk_out\": 0,
\"sales\": 0,
\"balance\": 1
}
]"
I need to iterate each line getting the id, barcode, nsr, etc and their values. I am using Newtonsoft but can't use their example Movie m = JsonConvert.DeserializeObject<Movie>(json);
I tried var m = JsonConvert.DeserializeObject<JValue>(json); It does get return the JSON line. For somereason m.Value is a string type. Any ideas how I can iterate this?
Since the json string defined in your example represent collection so you have to deserialize to List. I have created this dotnet fiddle to demonstrate your scenario. You can check the output in fiddle.
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string json = "[{\"id\":1,\"barcode\":\"TestBARCODE\",\"nsr\":0,\"stk_in\":0,\"stk_out\":0,\"sales\":0,\"balance\":1},{\"id\":2,\"barcode\":\"TestBARCODE2\",\"nsr\":0,\"stk_in\":0,\"stk_out\":0,\"sales\":0,\"balance\":1},{\"id\":3,\"barcode\":\"TestBARCODE3\",\"nsr\":0,\"stk_in\":0,\"stk_out\":0,\"sales\":0,\"balance\":1},{\"id\":4,\"barcode\":\"AAA\",\"nsr\":0,\"stk_in\":0,\"stk_out\":0,\"sales\":0,\"balance\":1},{\"id\":5,\"barcode\":\"BBB\",\"nsr\":0,\"stk_in\":0,\"stk_out\":0,\"sales\":0,\"balance\":1}]";
var movies = JsonConvert.DeserializeObject<List<Movie>>(json);
foreach (var movie in movies)
{
Console.WriteLine("Movie Id : " + movie.Id + " BarCode : " + movie.Barcode);
}
}
}
public class Movie
{
public int Id {get; set; }
public string Barcode {get; set; }
public int NSR {get; set; }
public int Stk_in {get; set; }
public int Stk_out {get; set; }
public int Balance {get; set; }
}
In Addition to #StriplingWarriors solution: I guess your declaration of Movie doesn't fit the json string. Define your class like the following:
// tip: use a tool like http://json2csharp.com/ to avoid typos etc.
public class MyObject
{
public int id {get;set;}
public string barcode {get;set;}
public int nsr {get;set;}
public int stk_in {get;set;}
public int stk_out {get;set;}
public int sales {get;set;}
public int balance {get;set;}
}
And then deserialize your json into a List of your class like so:
var m = JsonConvert.DeserializeObject<List<MyObject>>(json);
JValues can only represent primitive values like strings and numbers, so when you deserialize a string into a JValue, it makes sense that it would become a string-backed value.
Try this instead:
var m = JsonConvert.DeserializeObject<JArray>(json);
Then:
foreach(var item in m)
{
Console.WriteLine(item["id"]);
...
}
Try this:
public class Data
{
public int id { get; set; }
public string barcode { get; set; }
public int nsr { get; set; }
public int stk_in { get; set; }
public int stk_out { get; set; }
public int sales { get; set; }
public int balance { get; set; }
}
public class RootObject
{
public List<Data> data { get; set; }
}
RootObject objRootObject = JsonConvert.DeserializeObject<RootObject>(json);
if (objRootObject.data.Count > 0)
{
foreach (var item in objRootObject.data)
{
Console.WriteLine(item.id);
Console.WriteLine(item.barcode);
Console.WriteLine(item.nsr);
}
}
This is really definitely helpful to you.

NewtonSoft.Json Parse json callback

I have this callback
{
"status": "200",
"name": "Something Here",
"serverversion": "v1.2.4.1",
"tshockversion": {
"Major": 4,
"Minor": 2,
"Build": 4,
"Revision": 128,
"MajorRevision": 0,
"MinorRevision": 128
},
"port": 7777,
"playercount": 27,
"maxplayers": 60,
"world": "Something Here",
"uptime": "0.05:14:08",
"serverpassword": false
}
Windows Form Application, so i need to write on label1 like this: 27 from 60.
Help me, please.
So you want to parse a json response and display the text playercount + " from " + maxplayers on a label. yes?
First you need a strongly typed class. Use a tool like json2sharp to define the class and save it to your project.
public class Tshockversion
{
public int Major { get; set; }
public int Minor { get; set; }
public int Build { get; set; }
public int Revision { get; set; }
public int MajorRevision { get; set; }
public int MinorRevision { get; set; }
}
public class JsonResponse
{
public string status { get; set; }
public string name { get; set; }
public string serverversion { get; set; }
public Tshockversion tshockversion { get; set; }
public int port { get; set; }
public int playercount { get; set; }
public int maxplayers { get; set; }
public string world { get; set; }
public string uptime { get; set; }
public bool serverpassword { get; set; }
}
then, you can convert the json string and update your label
JsonResponse data = JsonConvert.DeserializeObject<JsonResponse>(json);
label1.Content = data.playercount + " from " + data.maxplayers
Why do you not simply follow the manual?
http://www.newtonsoft.com/json/help/html/SerializingJSON.htm
You may create a class, deserialize it and then you can access the properties of the deserialized object from the response you've got.
Assuming that json_response is a string containing the text from OP ...
string json_response = {
"status": "200",
"name": "Something Here",
"serverversion": "v1.2.4.1",
"tshockversion": {
"Major": 4,
"Minor": 2,
"Build": 4,
"Revision": 128,
"MajorRevision": 0,
"MinorRevision": 128
},
"port": 7777,
"playercount": 27,
"maxplayers": 60,
"world": "Something Here",
"uptime": "0.05:14:08",
"serverpassword": false
}
... then using Newtonsoft.Json.Linq JToken.Parse() Method which lets you parse either JObject or JArray objects ...
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
... you can try this ...
JObject data = (JObject)JToken.Parse(json_response);
label1.Content = data["playercount"].ToString() + " from " +
data["maxplayers"].ToString();
References
Json.NET
Json.NET Documentation
LINQ to JSON
Parsing JSON
Querying JSON with LINQ
JToken.Item Property
Newtonsoft.Json.Linq Namespace
Have you tried:
....
"uptime": "0.05:14:08",
"serverpassword": false,
"label1" : function(){return playercount + ' from ' + maxplayers;}
}
Is that what you wanted?

Parsing JSON with JObject

I need to parse a JSON, I am already parsing the first part of the record but I am having a problem with a sub record. This is my code:
List<JToken> results = new List<JToken>();
List<JToken> results2 = new List<JToken>();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
results = JObject.Parse(result).SelectToken("record").ToList();
}
List<Record> users = new List<Record>();
foreach (JObject token in results)
{
Record user = new Record();
user.id = Int32.Parse(token["id"].ToString());
user.full_name = token["full_name"].ToString();
user.email = token["email"].ToString();
//role.RoleName = token.SelectToken("name").ToString();
}
That's working perfectly but I have issues parsin a string that's a bit deeper. This is the JSON:
{
"record": [
{
"id": 2,
"institution_id": 1,
"full_name": "",
"email": "",
"role_id": 2,
"created": "2015-01-13 01:18:52.370379",
"updated": "2015-01-22 23:58:44.103636",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "Test Branch"
}
}
]
}
I want to get the "branch_name" inside Branch_by_branch_id. How can I access it with Jobject?
If your JSON is this
{
"record": [
{
"id": 26,
"full_name": "",
"email": "",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "NAME"
}
}
]
}
Have classes like this:
public class BranchByBranchId
{
public int id { get; set; }
public int institution_id { get; set; }
public string branch_name { get; set; }
}
public class Record
{
public int id { get; set; }
public string full_name { get; set; }
public string email { get; set; }
public int branch_id { get; set; }
public BranchByBranchId Branch_by_branch_id { get; set; }
}
public class RootObject
{
public List<Record> record { get; set; }
}
Then parse it and retrieve the value like this.
var root = JsonConvert.DeserializeObject<RootObject>(json);
var branchName = root[0].Branch_by_branch_id.branch_name;
I always prefer to access my JSON objects like this, because I like having my objects as native C# classes. The classes were generated by json2csharp.

Categories

Resources