Write Custom c# class to represent the JSON? - asp.net

I have a JSON string for which I need to create the C# class and then parse the entire List in similar format. JSON String contain "0" and "1". I have annotated the class properties with
[JsonProperty("0")]
but look like its not working.
{
"draw": 4,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
{
"0": "Charde",
"1": "Marshall",
"2": "Regional Director",
"3": "San Francisco",
"4": "16th Oct 08",
"5": "$470,600",
"DT_RowId": "row_13"
},
{
"0": "Colleen",
"1": "Hurst",
"2": "Javascript Developer",
"3": "San Francisco",
"4": "15th Sep 09",
"5": "$205,500",
"DT_RowId": "row_9"
},
{
"0": "Dai",
"1": "Rios",
"2": "Personnel Lead",
"3": "Edinburgh",
"4": "26th Sep 12",
"5": "$217,500",
"DT_RowId": "row_20"
}]
}
Class that I have tried for this JSON
public class UserData
{
[JsonProperty("0")]
public string Name { get; set; }
[JsonProperty("1")]
public string Email { get; set; }
//Having more JSON properites
[JsonProperty("DT_RowId")]
public long UserId { get; set; }
}
public class JsonValdate
{
public string draw { get; set; }
public int length { get; set; }
public int start { get; set; }
public int recordsFiltered { get; set; }
public int recordsTotal { get; set; }
[JsonProperty("data")]
public UserData[] data { get; set; }
}

It might be that some of JSON data cannot be converted to UserData Properties.
Right off the bat, you can see "DT_RowId": "row_20" cannot be converted to long UserId.
Use try catch block outside of conversion, and see the exception.
For example,
private string Json
{
get {
return #"
{
""draw"": 4,
...
}";
}
}
try
{
JsonValdate result = JsonConvert.DeserializeObject<JsonValdate>(Json);
}
catch (Exception ex)
{
// Debug
}
Here is how I test
Since the conversion is not working, do not put all fields at once.
Start with the following working fields. Then add one field at a time.
private string Json
{
get { return #"
{
""draw"": 4,
""recordsTotal"": 57,
""recordsFiltered"": 57,
""data"": [
{
""0"": ""Charde"",
""1"": ""Marshall""
},
{
""0"": ""Colleen"",
""1"": ""Hurst""
},
{
""0"": ""Dai"",
""1"": ""Rios""
}]
}";
}
}
public class UserData
{
[JsonProperty("0")]
public string Name { get; set; }
[JsonProperty("1")]
public string Email { get; set; }
}
public class JsonValdate
{
public string draw { get; set; }
public int length { get; set; }
public int start { get; set; }
public int recordsFiltered { get; set; }
public int recordsTotal { get; set; }
[JsonProperty("data")]
public UserData[] data { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
JsonValdate result = JsonConvert.DeserializeObject<JsonValdate>(Json);
}
catch (Exception ex)
{
}
}

Related

JSON.NET error "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type because the type requires a JSON object (e.g. {"name":"value"})"

I have the following WebCleint to call a Restful web service inside my .net console application:-
try
{
using (WebClient wc = new WebClient())
{
wc.Encoding = Encoding.UTF8;
string url = "https://*****/paged?hapikey=*********&properties=website&properties=i_scan&limit=2";//web service url
string tempurl = url.Trim();
var json = wc.DownloadString(tempurl);//get the json
Marketing ipfd = JsonConvert.DeserializeObject<Marketing>(json);//deserialize
}
}
catch (Exception e)
{
//code goes here..
}
where i am using JSON.Net to Deserialize the json object, which will be as follow:-
{
"has-more": true,
"offset": 622438650,
"companies": [
{
"portalId": *******,
"companyId": *****,
"isDeleted": false,
"properties": {
"website": {
"value": "****.net",
"timestamp": 1520938239457,
"source": "CALCULATED",
"sourceId": null,
"versions": [
{
"name": "website",
"value": "*****.net",
"timestamp": 1520938239457,
"source": "CALCULATED",
"sourceVid": [
731938234
]
}
]
}
},
"additionalDomains": [],
"stateChanges": [],
"mergeAudits": []
},
{
"portalId": ******,
"companyId": ******,
"isDeleted": false,
"properties": {
"website": {
"value": "****.***.***",
"timestamp": 1512488590073,
"source": "CALCULATED",
"sourceId": null,
"versions": [
{
"name": "website",
"value": "****.***8.****",
"timestamp": 1512488590073,
"source": "CALCULATED",
"sourceVid": []
}
]
},
"i_scan": {
"value": "Yes",
"timestamp": 1543409493459,
"source": "******",
"sourceId": "**************",
"versions": [
{
"name": "i_scan",
"value": "Yes",
"timestamp": 1543409493459,
"sourceId": *****",
"source": "CRM_UI",
"sourceVid": [],
"requestId": "******"
}
]
}
},
"additionalDomains": [],
"stateChanges": [],
"mergeAudits": []
}
]
}
Here are my classes:-
public class Marketing
{
public Companies companies { get; set; }
}
public class Companies
{
public IList<string> companyId { get; set; }
public IList<Properties> properties { get; set; }
}
public class Properties
{
public IList<Website> website { get; set; }
public IList<I_Scan> i_scan { get; set; }
}
public class Website
{
public string value { get; set; }
}
public class i_Scan
{
public string value { get; set; }
}
but currently i am getting this exception, when i try to de-serialize the JSON object:-
Newtonsoft.Json.JsonSerializationException was caught
HResult=-2146233088
Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MMarketing.Companies' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'companies', line 1, position 49.
Source=Newtonsoft.Json
StackTrace:
so i am not sure why JSON.NET is unable to do the Deserialize correctly, as in my case the classes are compatible with the returned json object??
At a first glance it looks like you switched two properties in Making them a List and vice versa.
public class Marketing
{
public List<Companies> companies { get; set; }
}
Is "companies": [ in the json, while "companyId": *****, is the id as a string, not array. Properties is not an array also, but the property versions of properties is.
public class Companies
{
public string companyId { get; set; }
public Properties properties { get; set; }
}
If I'm coming to json blind I like to use http://json2csharp.com/ to generate my class structure for me
public class Version
{
public string name { get; set; }
public string value { get; set; }
public object timestamp { get; set; }
public string source { get; set; }
public List<object> sourceVid { get; set; }
}
public class Website
{
public string value { get; set; }
public object timestamp { get; set; }
public string source { get; set; }
public object sourceId { get; set; }
public List<Version> versions { get; set; }
}
public class Version2
{
public string name { get; set; }
public string value { get; set; }
public long timestamp { get; set; }
public int sourceId { get; set; }
public string source { get; set; }
public List<object> sourceVid { get; set; }
public int requestId { get; set; }
}
public class IScan
{
public string value { get; set; }
public long timestamp { get; set; }
public int source { get; set; }
public int sourceId { get; set; }
public List<Version2> versions { get; set; }
}
public class Properties
{
public Website website { get; set; }
public IScan i_scan { get; set; }
}
public class Company
{
public int portalId { get; set; }
public int companyId { get; set; }
public bool isDeleted { get; set; }
public Properties properties { get; set; }
public List<object> additionalDomains { get; set; }
public List<object> stateChanges { get; set; }
public List<object> mergeAudits { get; set; }
}
public class Marketing
{
public bool has_more { get; set; }
public int offset { get; set; }
public List<Company> companies { get; set; }
}
var result = JsonConvert.DeserializeObject<Marketing>(json);

how to json convert to object and get data loop

i have following json.. i was convert my json into objectclass and get subjectid and class id loop through but its not working. i want subjectid and classid please help me how do this.i am new in c# please help me i am very thanful to you guys
[{
"teacherid": 1,
"teachername": "Addi Teacher",
"class": {
"class_id": 2,
"class_name": "Class 9"
},
"subjecname": {
"subject_id": 2,
"Subject_Name": "chemistry"
},
"$$hashKey": "object:10"
}, {
"teacherid": 1,
"teachername": "Addi Teacher",
"class": {
"class_id": 2,
"class_name": "Class 9"
},
"subjecname": {
"subject_id": 4,
"Subject_Name": "Science"
},
"$$hashKey": "object:12"
}, {
"teacherid": 1,
"teachername": "Addi Teacher",
"class": {
"class_id": 2,
"class_name": "Class 9"
},
"subjecname": {
"subject_id": 3,
"Subject_Name": "P.Study"
},
"$$hashKey": "object:14"
}]
//c# class
public class Class
{
public int class_id { get; set; }
public string class_name { get; set; }
}
public class Subjecname
{
public int subject_id { get; set; }
public string Subject_Name { get; set; }
}
public class RootObject
{
public int teacherid { get; set; }
public string teachername { get; set; }
public Class #class { get; set; }
public Subjecname subjecname { get; set; }
public string __invalid_name__$$hashKey { get; set; }
}
// code
subjectobject objsub = new JavaScriptSerializer().Deserialize<subjectobject>(jsonstring);
Do the following steps to achieve what you need:
Use my answer here to generate the C# classes for your JSON. The one you have created manually does not reflect your JSON accurately.
Use NewtonSoft NuGet package to deserialize from json to C# type
Then using Linq or a loop get the properties you need.
Here is what you r code will look like:
var obj = JsonConvert.DeserializeObject<Rootobject>("your json");
var result = obj.Property1.Select(x =>
new { ClassId = x._class.class_id, SubjectId = x.subjecname.subject_id });
By the way, this is what my linked answer will generate for you:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public int teacherid { get; set; }
public string teachername { get; set; }
public Class2 _class { get; set; }
public Subjecname subjecname { get; set; }
public string hashKey { get; set; }
}
public class Class2
{
public int class_id { get; set; }
public string class_name { get; set; }
}
public class Subjecname
{
public int subject_id { get; set; }
public string Subject_Name { get; set; }
}

WCF DeSerialize form-urlencode data into Class Object

I want to DeserializeObject of x-www-form-urlencoded string
public void TestData1(Stream data)
{
StreamReader sr = new StreamReader(data);
string strJson = sr.ReadToEnd();
var response = Newtonsoft.Json.JsonConvert.DeserializeObject<Recipe>strJson);
}
Below is my Request application/x-www-form-urlencoded
title=test&recipe_accessories=%5B+++++%7B+++++%22accessories_id%22%3A%22ingr001%22+++++++%7D%2C++++++%7B+++++%22ingredient_id%22%3A%22ingr001%22+++++%7D%2C++++++%7B+++++%22ingredient_id%22%3A%22ingr001%22+++++%7D+++%5D&recipe_ingredient=%5B+++++%7B+++++%22ingredient_id%22%3A%22ingr001%22%2C+++++%22ingredient_qty_num%22%3A%222.5%22%2C+++++%22ingredient_qty_unit%22%3A%22cup%22++++++++++++%7D%2C++++++%7B+++++%22ingredient_id%22%3A%22ingr001%22%2C+++++%22ingredient_qty_num%22%3A%222.5%22%2C+++++%22ingredient_qty_unit%22%3A%22cup%22++++++++++++%7D%2C++++++%7B+++++%22ingredient_id%22%3A%22ingr001%22%2C+++++%22ingredient_qty_num%22%3A%222.5%22%2C+++++%22ingredient_qty_unit%22%3A%22cup%22++++++++++++%7D+++%5D&recipe_img=%5B+++++%22http%3A%2F%2Fcontrol%2Fimages%2Ftest.jpg%22%2C+++++%22http%3A%2F%2Fcontrol%2Fimages%2Ftest.jpg%22%2C+++++%22http%3A%2F%2Fcontrol%2Fimages%2Ftest.jpg%22%2C+++++%22http%3A%2F%2Fcontrol%2Fimages%2Ftest.jpg%22%2C+++++%22http%3A%2F%2Fcontrol%2Fimages%2Ftest.jpg%22+++%5D
Error
Error parsing boolean value. Path '', line 1, position 1.'. See server logs for more details. The exception stack trace is: at Json.JsonTextReader.ParseTrue()
Actual Json in Raw format
{
"recipe_img": [
"http://control/images/test.jpg",
"http://control/images/test.jpg",
"http://control/images/test.jpg",
"http://control/images/test.jpg",
"http://control/images/test.jpg"
],
"recipe_ingredient": [
{
"ingredient_id":"ingr001",
"ingredient_qty_num":"2.5",
"ingredient_qty_unit":"cup"
},
{
"ingredient_id":"ingr001",
"ingredient_qty_num":"2.5",
"ingredient_qty_unit":"cup"
},
{
"ingredient_id":"ingr001",
"ingredient_qty_num":"2.5",
"ingredient_qty_unit":"cup"
}
],
"recipe_accessories": [
{
"accessories_id":"ingr001"
},
{
"ingredient_id":"ingr001"
},
{
"ingredient_id":"ingr001"
}
],
"title": "Hello WOrld",
}
When I use the BodyStyle = WebMessageBodyStyle.Bare and pass the Json in RAW format it works fine.
It will not work when the BodyStyle = WebMessageBodyStyle.WrappedRequest
Here is my Class
public class Recipe
{
public IList<string> recipe_img { get; set; }
public IList<RecipeIngredient> recipe_ingredient { get; set; }
public IList<RecipeAccessory> recipe_accessories { get; set; }
public string title { get; set; }
}
public class RecipeIngredient
{
public string ingredient_id { get; set; }
public string ingredient_qty_num { get; set; }
public string ingredient_qty_unit { get; set; }
}
public class RecipeAccessory
{
public string accessories_id { get; set; }
public string ingredient_id { get; set; }
}

Deserializing JSON to a .NET object puts null in each member of my object, why?

I am using JSON.NET (Newtonsoft.Json) to deserialize my JSON into a .NET object - here's my JSON string:
{
"SafetyReport": {
"SafetyData": [{
"Unsafe": "YES",
"CategoryName": "Body Mechanics",
"CategoryData": "Grip / Force",
"Safe": "NO"
}, {
"Unsafe": "YES",
"CategoryName": "Position of People",
"CategoryData": "Falling",
"Safe": "NO"
}, {
"Unsafe": "YES",
"CategoryName": "Position of People",
"CategoryData": "Other",
"Safe": "YES"
}],
"SafeActsObserved": "APPLE",
"UnsafeActsObserved": "OK",
"Date": "11 / 11 / 1988",
"ObserverName": "Bob",
"ObserverGroup": "TEST",
"LocationAreaRegion": "Nowhere",
"Email": "abc#abc.com"
}
}
Here's my C# code - please note that the jsonData string contains exactly the JSON above, just in a single line. I've already verified this:
Once I step past the deserialization, here's what's in my SafetyReport object:
Finally, here are my class definitions for SafetyReport and SafetyData:
public class SafetyReport
{
IList<SafetyData> SafetyData { get; set; }
string SafeActsObserved { get; set; }
string UnsafeActsObserved { get; set; }
string Date { get; set; }
string ObserverName { get; set; }
string ObserverGroup { get; set; }
string LocationAreaRegion { get; set; }
string Email { get; set; }
}
public class SafetyData
{
string Unsafe { get; set; }
string Safe { get; set; }
string CategoryName { get; set; }
string CategoryData { get; set; }
}
QUESTION: What am I doing wrong?
Ok I got it working, multiple things might have been wrong, here's what I did:
Added public modifier to every field.
Removed Safetyreport from JSON
Changed all doublequotes(") to quotes (')
Try this:
class Program
{
static void Main(string[] args)
{
string json = #"{
'SafetyData': [{
'Unsafe': 'YES',
'CategoryName': 'Body Mechanics',
'CategoryData': 'Grip / Force',
'Safe': 'NO'
}, {
'Unsafe': 'YES',
'CategoryName': 'Position of People',
'CategoryData': 'Falling',
'Safe': 'NO'
}, {
'Unsafe': 'YES',
'CategoryName': 'Position of People',
'CategoryData': 'Other',
'Safe': 'YES'
}],
'SafeActsObserved': 'APPLE',
'UnsafeActsObserved': 'OK',
'Date': '11 / 11 / 1988',
'ObserverName': 'Bob',
'ObserverGroup': 'TEST',
'LocationAreaRegion': 'Nowhere',
'Email': 'abc#abc.com'
}
";
SafetyReport sr = JsonConvert.DeserializeObject<SafetyReport>(json);
Console.ReadLine();
}
}
public class SafetyReport
{
public IList<SafetyData> SafetyData { get; set; }
public string SafeActsObserved { get; set; }
public string UnsafeActsObserved { get; set; }
public string Date { get; set; }
public string ObserverName { get; set; }
public string ObserverGroup { get; set; }
public string LocationAreaRegion { get; set; }
public string Email { get; set; }
}
public class SafetyData
{
public string Unsafe { get; set; }
public string Safe { get; set; }
public string CategoryName { get; set; }
public string CategoryData { get; set; }
}
Maybe the problem is the first field of the JSON, you haven't to set witch class you will deserialize, you have to set the attribute names to identify them. Try with this json.
{
"SafetyData": [{
"Unsafe": "YES",
"CategoryName": "Body Mechanics",
"CategoryData": "Grip / Force",
"Safe": "NO"
}, {
"Unsafe": "YES",
"CategoryName": "Position of People",
"CategoryData": "Falling",
"Safe": "NO"
}, {
"Unsafe": "YES",
"CategoryName": "Position of People",
"CategoryData": "Other",
"Safe": "YES"
}],
"SafeActsObserved": "APPLE",
"UnsafeActsObserved": "OK",
"Date": "11 / 11 / 1988",
"ObserverName": "Bob",
"ObserverGroup": "TEST",
"LocationAreaRegion": "Nowhere",
"Email": "abc#abc.com"
}
Hope it helps.

How to parse nested JSON string using .NET

I'm trying to parse a nested JSON string returned from the GCM (Google Could Messaging) server using VB.NET. The JSON string looks like this:
{ "multicast_id": 216,
"success": 3,
"failure": 3,
"canonical_ids": 1,
"results": [
{ "message_id": "1:0408" },
{ "error": "Unavailable" },
{ "error": "InvalidRegistration" },
{ "message_id": "1:1516" },
{ "message_id": "1:2342", "registration_id": "32" },
{ "error": "NotRegistered"}
]
}
I would like to get the results array in the above string.
I found the following example helpful, example but it does not show how to get to the nested parts, specifically message_id, error and registration_id inside the results array.
Thanks
I'll give an answer using c# and Json.net
var jobj = JsonConvert.DeserializeObject<Response>(json);
You can also use JavaScriptSerializer
var jobj2 = new JavaScriptSerializer().Deserialize<Response>(json);
public class Result
{
public string message_id { get; set; }
public string error { get; set; }
public string registration_id { get; set; }
}
public class Response
{
public int multicast_id { get; set; }
public int success { get; set; }
public int failure { get; set; }
public int canonical_ids { get; set; }
public List<Result> results { get; set; }
}

Resources