C# Json.net Unexpected character encountered while parsing value: [ - c#

public class JSON_Browse_Root
{
public string browse_content { get; set; }
public List<JSON_Browse_Content> Content { get; set; }
}
public class JSON_Browse_Content
{
public string link { get; set; }
public string image { get; set; }
public string title { get; set; }
public string description { get; set; }
public string rating { get; set; }
public string genre { get; set; }
}
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync("https://myjsonurl.com"))
using (HttpContent responseData = response.Content)
{
var jsonData = await responseData.ReadAsStringAsync();
var root = JsonConvert.DeserializeObject<JSON_Browse_Root>(jsonData);
}
}
JSON:
{
"browse_content": [
{
"link": "https:\/\/blah",
"image": "https:\/\/blahblah.blah.gif",
"title": "Mr. Southern Hospitality",
"description": "He got old money",
"rating": "e",
"author": "",
"genre": "Comedy - Original"
},
{
"link": "https:\/\/blah",
"image": "https:\/\/blahblah.blah.png",
"title": "Throwverwatch",
"description": "Based on the competitive overwatch experience",
"rating": "t",
"author": "",
"genre": "Comedy - Parody"
}
An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in
System.Private.CoreLib.ni.dll but was not handled in user code
Unexpected character encountered while parsing value: [
I used this JSON for iOS and Android apps and it's worked perfectly. Also, jsonlint.com says the JSON is valid. Not sure why it's erroring out on the [ character.

Assuming your JSON is missing the ending due to a copy/paste error, the actual problem you have is that your model class is wrong. You have a string property called browse_content and the deserialiser is trying to feed the array (i.e. the [...]) part of the JSON into it, hence you get the error about the unexpected character [. So the simple fix is to update your model to this:
public class JSON_Browse_Root
{
public List<JSON_Browse_Content> browse_content { get; set; }
}

Related

Getting NULL Deserializing JSON string using JavaScriptSerializer

Hi I having following JSON but while Using Deserialize method getting NULL in nested Member here is the sample JSON and corresponding Class object:
{
"status": "success",
"Info": [
{
"Name": "1099589",
"version": "Current Version",
"MoreDetails": [
{
"Name": "1099589",
"state": "IN"
},
{
"Name": "1099768",
"state": "OUT"
}
]
},
{
"Name": "1099768",
"version": "2019"
}
],
"errorCode": "",
"message": ""
}
Class :
public class MoreDetail
{
public string Name { get; set; }
public string state { get; set; }
}
public class Info
{
public string Name { get; set; }
public string version { get; set; }
public IList<MoreDetail> MoreDetails { get; set; }
}
public class Example
{
public string status { get; set; }
public IList<Info> Info { get; set; }
public string errorCode { get; set; }
public string message { get; set; }
}
While I am using
JavaScriptSerializer js = new JavaScriptSerializer();
Example ex = new OfferingPayload();
ex = js.Deserialize<Example> (jsonstring);
I am able to see Example object having Info data as list but MoreDetails member of Info Class is coming NULL.
Can someone suggest what I am missing here ?
Thats because your second "Info" object doesnt have "MoreDetails" property.
{
"Name": "1099768",
"version": "2019"
}
To make it works you can add an empty "MoreDetails" property to your json.
{
"Name": "1099768",
"version": "2019",
"MoreDetails": []
}
Or you can configure your serializer to handle this property as optional. Then it will works fine even if it missing in your json.

My MVC is not displaying the correct view when calling MakeRequest Method

I have the class below:
public class Product
{
[JsonProperty("image")]
public string ImageURL { get; set; }
[JsonProperty("superDepartment")]
public string SuperDepartment { get; set; }
[JsonProperty("tpnb")]
public long TPNB { get; set; }
[JsonProperty("ContentsMeasureType")]
public string ContentsMeasureType { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("UnitOfSale")]
public int UnitOfSale { get; set; }
[JsonProperty("description")]
public IEnumerator<string> LstDescription { get; set; }
public string Description { get; set; }
[JsonProperty("AverageSellingUnitWeight")]
public decimal AverageSellingUnitWeight { get; set; }
[JsonProperty("UnitQuantity")]
public string UnitQuantity { get; set; }
[JsonProperty("id")]
public long ID { get; set; }
[JsonProperty("ContentsQuantity")]
public int ContentsQuantity { get; set; }
[JsonProperty("department")]
public string Department { get; set; }
[JsonProperty("price")]
public decimal Price { get; set; }
[JsonProperty("unitprice")]
public decimal UnitPrice { get; set; }
}
I have the method on the productController:
public async Task<ActionResult> MakeRequest(string q)// worked
{
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "56ac439a92694577a2779f3d0ee0cd85");
var uri = string.Format("https://dev.tescolabs.com/grocery/products/?query={0}&offset={1}&limit={2}", q, 0, 10);
var response = await client.GetAsync(uri);
string body = await response.Content.ReadAsStringAsync();
Product myoutput = JsonConvert.DeserializeObject<Product>(body);
}
return View(body);
}
and I have the model below:
For some reason when I call the method MakeRequest it just shows the information as a string and an error saying Server Error as per picture below we can see the information from the api but it is showing as a string.
error message
The information from the api it should be showing on the table below:
table
How to show the data on the table? Or better how to convert the json array to a net object?
I know there is something missing in the part below of my method:
Product myoutput = JsonConvert.DeserializeObject<Product>(body);
You're passing json string to your View instead of your deserialized Product.
I assume your View expects model of type Product.
The return statement of MakeRequest action should be return View(myOutput);
I'll tell you in a simple way.
Your json model
-uk
--ghs
---products
----results
{
"uk" : {
"ghs" : {
"products": {
"input_query": "babana",
"output_query": "banana",
"filters": {},
"queryPhase": "post_primary",
"totals": {
"all": 109,
"new": 1,
"offer": 47
},
"config": "default",
"results": [
{
"image": "http://img.tesco.com/Groceries/pi/000/0261480000000/IDShot_90x90.jpg",
"superDepartment": "Fresh Food",
"tpnb": 50502269,
"ContentsMeasureType": "KG",
"name": "Tesco Bananas Loose",
"UnitOfSale": 3,
"description": [ "To help ensure the banana farms we source from are best in class we, and our", "suppliers, now work closely with the Rainforest Alliance, an international", "non profit organisation that works to conserve biodiversity and ensure", "sustainable livelihoods worldwide.", "The Rainforest Alliance Certified™ seal on our bananas a green frog nestled", "in a circle – helps us to tell the story of how they are sustainably sourced,", "and assure customers we are sourcing from responsibly managed farms." ],
"AverageSellingUnitWeight": 2.402,
"UnitQuantity": "KG",
"id": 275280804,
"ContentsQuantity": 1,
"department": "Fresh Fruit",
"price": 0.76,
"unitprice": 0.76
},
{
"image": "http://img.tesco.com/Groceries/pi/875/0000010001875/IDShot_90x90.jpg",
"superDepartment": "Fresh Food",
"tpnb": 65728590,
"ContentsMeasureType": "SNGL",
"name": "Tesco Ripe Bananas 5 Pack",
"UnitOfSale": 1,
"AverageSellingUnitWeight": 0.862,
"UnitQuantity": "EACH",
"id": 266419328,
"ContentsQuantity": 5,
"department": "Fresh Fruit",
"price": 0.9,
"unitprice": 0.18
},
{
"image": "http://img.tesco.com/Groceries/pi/416/0000003251416/IDShot_90x90.jpg",
"superDepartment": "Fresh Food",
"tpnb": 77427870,
"ContentsMeasureType": "SNGL",
"name": "Tesco Small Bananas 6 Pack",
"UnitOfSale": 1,
"description": [ "Small Bananas", "Tesco Small Bananas" ],
"AverageSellingUnitWeight": 0.965,
"UnitQuantity": "EACH",
"id": 285157326,
"ContentsQuantity": 6,
"department": "Fresh Fruit",
"price": 0.9,
"unitprice": 0.15
}
],
"suggestions": []
}
}
}
}
If you look at the above json result, you need a more comprehensive model.
For this you can enter the json result into a model here. look here
or keep the result object from its current state with dynamic.
string body = response.Content.ReadAsStringAsync().Result;
dynamic content = JObject.Parse(body);
var products = content.uk.ghs.products.results;

Deserialise JSON array object with nested list in C#

I am trying to deserialise the live chat api json response to access the message id and text by filtering using user_type
JSON response
{{
"events": [
{
"type": "agent_details",
"message_id": 1,
"timestamp": 1532396384,
"user_type": "agent",
"agent": {
"name": "Adam Harris",
"job_title": "Support Agent",
"avatar": "livechat.s3.amazonaws.com/default/avatars/ab5b0666feffd67600206cd519fd77ea.jpg"
}
},
{
"type": "message",
"message_id": 3,
"timestamp": 1532396387,
"user_type": "visitor",
"text": "hi"
}
]
}}
JsonOject Class
class JsonLiveChatEvent
{
public class Rootobject
{
public Event[] events { get; set; }
}
public class Event
{
public string type { get; set; }
public int message_id { get; set; }
public int timestamp { get; set; }
public string user_type { get; set; }
public Agent agent { get; set; }
public string text { get; set; }
}
public class Agent
{
public string name { get; set; }
public string job_title { get; set; }
public string avatar { get; set; }
}
}
JsonConverter
string jsonStr= await Api.Chat.GetPendingMessages(visitorID, licenseID,
var chatEvent = JsonConvert.DeserializeObject<Rootobject>(jsonStr);
The chatEvent object will not let me call chatEvent.events.message_id for example. Any help would be greatly appreciated as this is my first time working with json in c#
There is nothing to do with JSON, you have parsed the JSON data back to Rootobject.
Now you are working with an instance of Rootobject as:
Rootobject chatEvent = JsonConvert.DeserializeObject<Rootobject>(jsonStr);
Event event1 = chatEvent.events[0];
Event event2 = chatEvent.events[1];
Also, consider the answer from Mohammad, because above JSON will throw an exception.
The main problem here is that your json is not valid, there is an extra { in the beginning and an extra } in the end.
Then you could deserialize your json with the types you provided
Your json contains more that one curly brackets so you have to first remove those
so your json look like
{
"events": [
{
"type": "agent_details",
"message_id": 1,
"timestamp": 1532396384,
"user_type": "agent",
"agent": {
"name": "Adam Harris",
"job_title": "Support Agent",
"avatar": "livechat.s3.amazonaws.com/default/avatars/ab5b0666feffd67600206cd519fd77ea.jpg"
}
},
{
"type": "message",
"message_id": 3,
"timestamp": 1532396387,
"user_type": "visitor",
"text": "hi"
}
]
}
After that you have to collect message ids depending upon user_type
So then we create enum for that
public enum UserType
{
agent, visitor
}
then we simply check in events that if user type is matches with any of above enum value.
If your json contains multiple events with multiple user types then collect those into List<int>.
If your json contains only single event of each user type then collect them into string variables.
Rootobject chatEvent = JsonConvert.DeserializeObject<Rootobject>(jsonStr);
List<int> agent_message_ids = new List<int>();
List<int> visitior_message_ids = new List<int>();
//string agent_message_id = string.Empty;
//string visitior_message_id = string.Empty;
foreach (Event e in chatEvent.events)
{
if (e.user_type == UserType.agent.ToString())
{
agent_message_ids.Add(e.message_id);
//agent_message_id = e.message_id;
}
if (e.user_type == UserType.visitor.ToString())
{
visitior_message_ids.Add(e.message_id);
//visitior_message_id = e.message_id;
}
}
We simply take a list of integers that store message ids for particular user_type
Try once may it help you
Result:
agent_message_ids:
visitor_message_ids:

Can I deserialize a JSON object by object in C#?

I have a big json file. It consist of information of different articles posted on internet. I'm wandering if it's possible to deserialize it object by object. For example, to make a loop and with every iteration a single object from json to be deserialized, then the next one, and so on.
Here are just only two of json file's objects (there are some thousands out there)
[
{
"source": "unimedia",
"title": "some title",
"original_time": "ora: 20:03, 06 dec 2006",
"datetime": "2006-12-06T20:03:00+00:00",
"views": 398,
"comments": 1,
"content": " some content",
"id": "13",
"url": "http://unimedia.info/stiri/-13.html"
},
{
"source": "unimedia",
"title": "some another title",
"original_time": "ora: 20:13, 06 dec 2006",
"datetime": "2006-12-06T20:13:00+00:00",
"views": 173,
"comments": 1,
"content": "some another content",
"id": "19",
"url": "http://unimedia.info/stiri/-19.html"
},
...
]
Here is my class:
class jsonData
{
public string source { get; set; }
public string title { get; set; }
public string original_time { get; set; }
public string datetime { get; set; }
public int views { get; set; }
public int comments { get; set; }
public string content { get; set; }
public int id { get; set; }
public string url { get; set; }
}
Can anybody help me with that ?
You just need to use use Newtonsoft.Json
Newtonsoft Json
string json = File.ReadAllText(PathFile);
jsonData obj = JsonConvert.DeserializeObject<jsonData>(json);

Convert from JSon to Object Collection

Below is my json string, which i am trying to parse to list of my class
i am using NewtonsJson.net.3.5
[
{
"message": {
"$": "#12:55 Big Rally on South Bound of Dr. B.A. Road. Motorists may use RAK Road, P. D'Melow Road & A.B. Road for CST.\n -visit icicilombard.com"
},
"picture": {
"$": ""
},
"medium": {
"$": "API"
},
"timestamp": {
"$": "03\/15\/2011 12:55:42 IST"
}
}
]
This is my class of which i want my json to be parsed to
public class GupShupTrafficAlerts
{
private string _message = string.Empty;
private string _picture = string.Empty;
private string _medium = string.Empty;
private string _timeStamp = string.Empty;
public String message
{
get;
set;
}
public string timestamp
{
get;
set;
}
public string medium
{
get;
set;
}
public string picture
{
get;
set;
}
}
this is the way i m trying to parse to List
List<GupShupTrafficAlerts> lstTrafficAlert =
JsonConvert.DeserializeObject<List<GupShupTrafficAlerts>>(#JSonString);
but to no avail
Please help me...
Your JSON should look like that:
[
{
"message": "#12:55 Big Rally on South Bound of Dr. B.A. Road. Motorists may use RAK Road, P. D'Melow Road & A.B. Road for CST.\n -visit icicilombard.com",
"picture": "",
"medium": "API",
"timestamp":"03\/15\/2011 12:55:42 IST"
}
]

Categories

Resources