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; }
}
Related
I am sending data in a post request as follow:
{
"HospitalId": "Hospital-0232",
"DataSliceTimestamp": "2020.08.10",
"HourQuarter": "00:01",
"Data": [
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2014,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2015,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2016,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2017,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"},
{"country":"US","state":"MS","county":"bolivar","lat":32.354668,"lng":-89.398528,"type":"ICU","measure":"1000HAB","beds":0.241539,"population":33121,"year":2018,"source":"khn","source_url":"https://khn.org/news/as-coronavirus-spreads-widely-millions-of-older-americans-live-in-counties-with-no-icu-beds/"}
]
}
And for reading the body I am doing it like this:
public class RequestBody
{
public string HospitalId { get; set; }
public string DataSliceTimestamp { get; set; }
public string HourQuarter { get; set; }
public string[] Data { get; set; }
}
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
RequestBody data = JsonConvert.DeserializeObject<RequestBody>(requestBody);
But I get error:
Newtonsoft.Json: Unexpected character encountered while parsing value: [. Path 'Data', line 5, position 13.
Something is wrong while reading array data, please guide.
You need to strongly type your JSON input to an object array not a string.
Here's an example of what the object could look like:
public class Datum
{
[JsonProperty("country")]
public string country { get; set; }
[JsonProperty("state")]
public string state { get; set; }
[JsonProperty("county")]
public string county { get; set; }
[JsonProperty("lat")]
public double lat { get; set; }
[JsonProperty("lng")]
public double lng { get; set; }
[JsonProperty("type")]
public string type { get; set; }
[JsonProperty("measure")]
public string measure { get; set; }
[JsonProperty("beds")]
public double beds { get; set; }
[JsonProperty("population")]
public int population { get; set; }
[JsonProperty("year")]
public int year { get; set; }
[JsonProperty("source")]
public string source { get; set; }
[JsonProperty("source_url")]
public string source_url { get; set; }
}
public class RequestBody
{
[JsonProperty("HospitalId")]
public string HospitalId { get; set; }
[JsonProperty("DataSliceTimestamp")]
public string DataSliceTimestamp { get; set; }
[JsonProperty("HourQuarter")]
public string HourQuarter { get; set; }
[JsonProperty("Data")]
public IList<Datum> Data { get; set; }
}
You can then deserialize it like you're already doing:
RequestBody data = JsonConvert.DeserializeObject<RequestBody>(requestBody);
I solved this by using dynamic type and by pulling out data field from the request body.
// Reading body
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
// Parse through the request body string and make it in appropriate format.
dynamic RequestBody_data = JsonConvert.DeserializeObject(requestBody);
var Data = RequestBody_data["Data"].ToString();
Through this I was able to get the data field string and then I can split it with "}," to get all the rows. Thanks
Hello I am getting JSON data from server and i want to extract that JSON in Xamarin. How can i parse that JSON using NewTonSoft
below is the JSON responce i receive
[
{
"Id": 5,
"AlbumKey": "2REC2ZDSFK",
"ZipFillPath": "aaaa#gmail.com\\2REC2ZDSFK",
"NoOfPages": 3,
"EmailID": "aaaa#gmail.com"
}
]
This should be your Model
public class RootObject
{
public int Id { get; set; }
public string AlbumKey { get; set; }
public string ZipFillPath { get; set; }
public int NoOfPages { get; set; }
public string EmailID { get; set; }
}
Then
RootObject myObj = JsonConvert.DeserializeObject<RootObject>(json);
If your json is a List of objects, something like
List<RootObject> myListObj = JsonConvert.DeserializeObject<List<RootObject>>(json);
public class yourClass
{
public int Id { get; set; }
public string AlbumKey { get; set; }
public string ZipFillPath { get; set; }
public int NoOfPages { get; set; }
public string EmailID { get; set; }
}
Considering this as your model class you can
var responseText= JsonConvert.DeserializeObject<yourClass>(jsonResponse);
Then depending on if its a list or a not you can get the data from it
In case you are unable to find the class what you can do is check if the namespace of your current class and that class is the same.
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.
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.
I am having some issues DeSerializing the following Json, it runs, throws no errors however the props in the class are all null so it is obviously not working.
{ "realms":[ { "type":"pve", "queue":false, "status":true, "population":"medium", "name":"Malfurion", "slug":"malfurion" } ] }
The above JSON is the jsonResult string so string jsonResult = the above JSON
My code:
public class Realm
{
public string type { get; set; }
public bool queue { get; set; }
public bool status { get; set; }
public string population { get; set; }
public string name { get; set; }
public string slug { get; set; }
}
var realm = javaScriptSerializer.Deserialize<Realm>(jsonResult);
There are no props in the object because the object contains a single array with a single object in the array.