Parsing JSON in C# 4.0 - json

Can anyone help me to parse this JSON into an object IN C# 4.0. I have spent the last two days trying.
I have JSON.NET and several other peoples suggestions to no avail.
I thought it would be best just to give the JSON sample and to ask for your suggestions.
{
"message-count":"1",
"messages":[
{"to":"441234567890",
"messageprice":"0.02900000",
"status":"0",
"messageid":"030000001DFE2CB1",
"remainingbalance":"1.56500000",
"network":"23433"}
]
}
Many thanks,
Adrian
p.s Their is some nice code here, if you want to use github. https://github.com/lukesampson/HastyAPI.Nexmo

I will cheat and create C# classes quickly using this tool: http://json2csharp.com/ (or just discovered http://jsonclassgenerator.codeplex.com/)
Then I change C# classes to my liking
public class MessagesJSON
{
public int MessageCount { get; set; }
public List<Message> Messages { get; set; }
}
public class Message
{
public string To { get; set; }
public double MessagePrice { get; set; }
public int Status { get; set; }
public string MessageId { get; set; }
public double RemainingBalance { get; set; }
public string Network { get; set; }
}
MessagesJSON is just a name I made that represents the JSON object that you are passing to C#.
I pass the JSON string from the client, e.g.
{\"MessageCount\":1,\"Messages\":[{\"To\":\"441234567890\",\"MessagePrice\":0.029,\"Status\":0,\"MessageId\":\"030000001DFE2CB1\",\"RemainingBalance\":1.565,\"Network\":\"23433\"}]
Then I can use JSON.NET to convert JSON to C# objects:
public void YourMethod(MessagesJSON json) {
var result = JsonConvert.DeserializeObject<MessagesJSON>(json);
}
Here's the result:
Watch out for capitalisation.
If you want to use lower-case JSON keys only, change the C# classes to lower-case, e.g. public double messageprice { get; set; }
C# classes:
public class MessagesJSON
{
public int message_count { get; set; }
public List<Message> messages { get; set; }
}
public class Message
{
public string to { get; set; }
public string messageprice { get; set; }
public string status { get; set; }
public string messageid { get; set; }
public string remainingbalance { get; set; }
public string network { get; set; }
}
This is as close to your JSON as you want:
{\"message_count\":1,\"messages\":[{\"to\":\"441234567890\",\"messageprice\":\"0.02900000\",\"status\":\"0\",\"messageid\":\"030000001DFE2CB1\",\"remainingbalance\":\"1.56500000\",\"network\":\"23433\"}]}
or use one of these solutions if you really like CamelCasing:
CamelCase only if PropertyName not explicitly set in Json.Net?
JObject & CamelCase conversion with JSON.Net
I myself prefer attributes
public class Message
{
[JsonProperty("to")]
public string To { get; set; }
[JsonProperty("messageprice")]
public string MessagePrice { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("messageid")]
public string MessageId { get; set; }
[JsonProperty("remainingbalance")]
public string RemainingBalance { get; set; }
[JsonProperty("network")]
public string Network { get; set; }
}
Pass your string:
"{\"message_count\":1,\"messages\":[{\"to\":\"441234567890\",\"messageprice\":\"0.02900000\",\"status\":\"0\",\"messageid\":\"030000001DFE2CB1\",\"remainingbalance\":\"1.56500000\",\"network\":\"23433\"}]}"
but get the pretty C# property names:

Create objects with the same structure as the json and call.
JsonConvert.DeserializeObject<Entity>(json);
Edit. You have to use JSON.NET if u wanna do it this way.

Related

JSON.NET Error reading string. Unexpected token: StartObject. Path 'responseData',

I am trying to deserialize this link , but I keep getting this error.
Error reading string. Unexpected token: StartObject. Path 'responseData'.
From what i have googled, the problem seems to be the setup of my object I'm trying to deserialize into. Below is my class:
public class FeedSearchResult
{
[JsonProperty("responseData")]
public String ResponseData { get; set; }
[JsonProperty("query")]
public String Query { get; set; }
[JsonProperty("entries")]
public string[] Entries { get; set; }
[JsonProperty("responseDetails")]
public object ResponseDetails { get; set; }
[JsonProperty("responseStatus")]
public String ResponseStatsu { get; set; }
}
public class ResultItem
{
[JsonProperty("title")]
public String Title { get; set; }
[JsonProperty("url")]
public String Url { get; set; }
[JsonProperty("link")]
public String Link { get; set; }
}
What am I doing wrong in my class? Any help would be greatly appreciated.
Your data model only has two levels of nesting, but the JSON returned has three. If you look at the formatted JSON using https://jsonformatter.curiousconcept.com/ you will see:
{
"responseData":{
"query":"Official Google Blogs",
"entries":[
{
"url":"https://googleblog.blogspot.com/feeds/posts/default",
"title":"\u003cb\u003eOfficial Google Blog\u003c/b\u003e",
"contentSnippet":"\u003cb\u003eOfficial\u003c/b\u003e weblog, with news of new products, events and glimpses of life inside \u003cbr\u003e\n\u003cb\u003eGoogle\u003c/b\u003e.",
"link":"https://googleblog.blogspot.com/"
},
In particular your data model has responseData as a String when it needs to be a contained object. This is the specific cause of the exception.
If you upload the JSON to http://json2csharp.com/ you will get the following data model, which can be used to deserialize this JSON:
public class ResultItem
{
public string url { get; set; }
public string title { get; set; }
public string contentSnippet { get; set; }
public string link { get; set; }
}
public class ResponseData
{
public string query { get; set; }
public List<ResultItem> entries { get; set; }
}
public class RootObject
{
public ResponseData responseData { get; set; }
//Omitted since type is unclear.
//public object responseDetails { get; set; }
public int responseStatus { get; set; }
}

Trying to check a json file for the correct parameters using JsonConvert.DeserisalizeObject<t>

I'm using the ACE code editor to gather Json and send it to my application. Once the Json hits the application, I need to make sure there are certain key's inside the json so I am using JsonConvert.DeserisalizeObject<t> to do this. Here's how:
public void SubmitReport(string JsonStringSend)
{
try
{
ReportItem RptItem = JsonConvert.DeserializeObject<ReportItem>(JsonStringSend);
}
catch(err)
{
return View(err);
}
}
and:
public class ReportItem
{
public Guid ReportID;
public bool RequiresFilter;
public string MimeType { get; set; }
public string ExternalID { get; set; }
public DateTime CreatedBy { get; set; }
public string ExecutionScript { get; set; }
public string ExecutionParameter { get; set; }
public string ExecutionOrderBy { get; set; }
public List<DynamicFilter> DynamicFilters { get; set; }
public bool RequiresOrgID { get; set; }
public QueryFilter ReportFilter { get; set; }
public QueryRule ReportRules { get; set; }
public List<QueryColumn> Columns { get; set; }
}
But for some reason, it bounces right over the catch even when I make sure some of the key's are incorrect. Am I not understanding the correct usage JsonConvert.DeserisalizeObject<t>? Or, is there a better way to be doing this check?
By default, the deserializer "tries it's best" to deserialize the object. But JSon.NET supports validation, the "straightforward" way is probably JSon Schema: http://www.newtonsoft.com/jsonschema.
Simple case can be handled with JSon.NET directly:
public class ReportItem
{
[JsonProperty(Required = Required.Always)]
public bool RequiresFilter;
[JsonProperty(Required = Required.Always)]
public string MimeType { get; set; }
public DateTime CreatedBy { get; set; }
public string ExecutionScript { get; set; }
public string ExecutionParameter { get; set; }
public string ExecutionOrderBy { get; set; }
public bool RequiresOrgID { get; set; }
}

Problems quering/deserializing multilevel field objects

https://opendata.miamidade.gov/Corrections/Jail-Bookings-May-29-2015-to-current/7nhc-4yqn?
I don't if someone could help me with this: I've been having problems parsing/de-serializing the Address information that comes inside the Location object.
This is a fragment of the code i am using:
var results = dataset.Query<MiamiDade_JailLog>(soql);
public class MiamiDade_JailLog
{
public string chargecode3 { get; set; }
public string charge2 { get; set; }
public string bookdate { get; set; }
public string charge3 { get; set; }
public string chargecode1 { get; set; }
public string chargecode2 { get; set; }
public string charge1 { get; set; }
public string dob { get; set; }
public Location1 location_1 { get; set; }
public string defendant { get; set; }
}
public class Location1
{
public bool needs_recoding { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
public HumanAddress human_address { get; set; }
}
public class HumanAddress
{
public string address { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
}
and this is the error message:
Error converting value
"{"address":"HOMELESS","city":"MIAMI","state":"FL","zip":""}" to type
'JailLog_WFA.HumanAddress'. Path 'location_1.human_address', line 1,
position 424.
This is the response I got from Socrata:
If you look at this json response, https://opendata.miamidade.gov/resource/7nhc-4yqn.json
You'll see that for the location_1 column, we provide an object, {}
and then within there you'll see human_address which we provide as a string "" instead of as an object.
For JavaScript, it would just be JSON.parse("{\"address\":\"17725 NW 8TH PL\",\"city\":\"MIAMI GARDENS\",\"state\":\"FL\",\"zip\":\"33169\"}");
From the code you sent, it looks like you are treating HumanAddress as an object instead of as a string that needs to be parsed into an object.
If you make this change it should work.
...And this was my response:
You gave me very good info. However I had already done a workaround to parse the object.
I just removed the extra quotes from the human_ address object and was able to parse everything at once.

Newtonsoft JSON deserialize and write data

I have the following class Visual Studio created from the JSON pasted below.
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string id { get; set; }
public string comments { get; set; }
public DateTime createdDate { get; set; }
public DateTime modifiedDate { get; set; }
public string createdBy { get; set; }
public string modifiedBy { get; set; }
}
-----JSON-----
[{"id":"00a17000000LmTOAA0","comments":"This is a comment or note added from code","createdDate":"2015-03-13T15:52:02.000+0000","modifiedDate":"2015-03-13T15:52:02.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmTTAA0","comments":"This is a comment or note added from code","createdDate":"2015-03-13T15:53:19.000+0000","modifiedDate":"2015-03-13T15:53:19.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmTYAA0","comments":"This is a comment or note added from code","createdDate":"2015-03-13T15:54:29.000+0000","modifiedDate":"2015-03-13T15:54:29.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmU7AAK","comments":"New Note Entered by Requester: This is a comment or note added from code","createdDate":"2015-03-13T16:39:43.000+0000","modifiedDate":"2015-03-13T16:39:43.000+0000","createdBy":"Contact","modifiedBy":"Contact"},{"id":"00a17000000LmW3AAK","comments":"added this comment from SalesF app as an agent","createdDate":"2015-03-13T17:37:24.000+0000","modifiedDate":"2015-03-13T17:37:24.000+0000","createdBy":"Agent","modifiedBy":"Agent"}]
I'm trying to create an object and do a foreach and get the data... I keep getting error Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {“name”:“value”}) to deserialize correctly.
I have tried this among other things:
var jsonResponseNotes = JsonConvert.DeserializeObject<Rootobject>(GetCommentsByID());
Any Ideas would be greatly appreciated!!!
you just need the root class:
public class RootObject
{
public string id { get; set; }
public string comments { get; set; }
public string createdDate { get; set; }
public string modifiedDate { get; set; }
public string createdBy { get; set; }
public string modifiedBy { get; set; }
}
and then deserialize it like this:
var result = JsonConvert.DeserializeObject<List<RootObject>>(json);
This is a list of your object. You will need to deserialize as such. Your code should be:
var jsonResponseNotes = JsonConvert.DeserializeObject<List<Class1>>(GetCommentsByID());
Edit
Just noticed your root object property is an array. Still, I believe arrays deserialize into list objects. I've adjusted my code.

How can I deserialization JSON in Windows Phone?

The first JSON is look like this
The second JSON is look like this
How can I deserialize them? I have been follow this example but it's not working.
Here's my code.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var w = new WebClient();
Observable
.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var deserialized =
JsonConvert.DeserializeObject<List<Place>>(r.EventArgs.Result);
PlaceList.ItemsSource = deserialized;
});
w.DownloadStringAsync(
new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place"));
//For 2nd JSON
//w.DownloadStringAsync(
//new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place/243"));
}
These are classes for 1st JSON.
public class Place
{
public string id { get; set; }
public string title { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
}
public class RootObjectJSON1
{
public List<Place> Places { get; set; }
}
These are classes for JSON2
public class Address
{
public string street { get; set; }
public string postal_code { get; set; }
public string post_office { get; set; }
}
public class Image
{
public string id { get; set; }
public string filename { get; set; }
public string path { get; set; }
}
public class RootObjectJSON2
{
public string id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string contact_person { get; set; }
public Address address { get; set; }
public List<Image> images { get; set; }
}
it looks that you should be deserializing object RootObjectJSON1 or RootObjectJSON2, e.g.:
var deserialized = JsonConvert.DeserializeObject<RootObjectJSON1>(r.EventArgs.Result);
Also it seems that collection Places should be with lowercase p at beginning or you need to tell Json.NET that this property should be deserialized with different name, e.g.:
[JsonProperty(PropertyName="places")]
public List<Place> Places { get; set; }
Generally I tend to use arrays for deserialization (from my experience works better) so I'll suggest to rewrite it to this:
public class RootObjectJSON1
{
public Place[] places { get; set; }
}
There is very good tool named json2csharp available at http://json2csharp.com/ - just put sample of JSON there and it will spit out classes in C# (doesn't detect DateTime so you might need to change that).