Convert from JSon to Object Collection - c#

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"
}
]

Related

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:

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

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; }
}

Multi-Object JSON, "Cannot deserialize the current JSON object"

Okay first of all, the answer is probably very simple... But after 45 minutes of trying and googling I just can't figure it out!
So I have some problems getting this Json to parse correctly. I created the classes with http://json2csharp.com/ only it doesn't tell me the code to parse it.
My current classes:
public class Representations
{
public string thumb { get; set; }
public string large { get; set; }
public string full { get; set; }
}
public class Search
{
public string id { get; set; }
public string file_name { get; set; }
public Representations representations { get; set; }
}
public class SearchQuery
{
public List<Search> search { get; set; }
public int total { get; set; }
}
JSON:
{
"search": [
{
"id": "0300",
"file_name": "0300.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0300.jpg"
},
},
{
"id": "0000",
"file_name": "0000.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0000.jpg"
},
},
{
"id": "0d00",
"file_name": "0d00.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0d00.jpg"
},
}
],
"total": 3
}
and code:
searchresults = JsonConvert.DeserializeObject<List<SearchQuery>>(JSONCode);
You should deserialize to a SearchQuery, not List<SearchQuery>:
SearchQuery result = JsonConvert.DeserializeObject<SearchQuery>(JSONCode);
and then use the search property to access the list of search results:
List<Search> searchResults = result.search;

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);

How can I use ReadAsAsync<T> with this data schema?

I am using System.Net.Http.HttpClient, the version currently available in NuGet,
to retrieve data from a service in json format. The data roughly looks like this:
{
"schema": "Listing",
"data": {
"key": "28ba648c-de24-45d4-a7d9-70f810cf5438",
"children": [{
"kind": "type1",
"data": {
"body": "Four score and seven years ago...",
"parent_id": "2qh3l",
"report_count": 0,
"name": "c4j6yeh"
}
}, {
"kind": "type3",
"data": {
"domain": "abc.def.com",
"flagged": true,
"category": "news",
"saved": false,
"id": "t3dz0",
"created": 1335998011.0
}
}]
}
}
I use HttpContentExtensions.ReadAsAsync<T> to de-serialize that json string into an object graph. The type definitions looks roughly like this:
public class Response
{
public String schema { get;set; }
public ListingData data { get;set; }
}
public class ListingData
{
public string key { get;set; }
public List<OneItem> children { get;set; }
}
Here's the problem: I desire the type of the items in children to vary depending on the kind property. If kind is "type1" then I want to de-serialize an object of... let's call it Type1 . If kind is "type3" then I want an object of type Type3.
Right now, I can deserialize a List<Type1> or a List<Type3>, but I don't know how to tell the de-serialization logic to distinguish between the two.
I could merge all the properties of the "type1" data object and the "type3" data object into a single .NET Type. But the number of properties is large enough that this gets messy.
If the name of the property in the JSON (in this case data) were different, I could distinguish using that. If, for example, the data looked like this:
"children": [{
"kind": "type1",
"t1data": { ... }
}, {
"kind": "type3",
"t3data": { ... }
}]
...then I could do something like this in .NET:
public class OneItem
{
public string kind { get;set; }
public Type1 t1data { get;set; }
public Type3 t3data { get;set; }
}
But my data schema doesn't look like that.
Is it possible to choose the type for de-serialization by the content of the data? In other words,
look at the value of one property (in this case, kind) to determine how to de-serialize the content for another property (in this case, data).
Or is it possible to inject a filter or transformer that acts on the JSON before ReadAsAsync tries to deserialize it?
If so, How?
If you're ok w/ doing some pre-processing on your response and you can use Json.NET, you should be able to do what you want.
Given the following classes:
public class Response
{
public string schema
{
get;
set;
}
public ListingData data
{
get;
set;
}
}
public class ListingData
{
public string key
{
get;
set;
}
public List<object> children
{
get;
set;
}
}
public class Type1
{
public string body
{
get;
set;
}
public string parent_id
{
get;
set;
}
public int report_count
{
get;
set;
}
public string name
{
get;
set;
}
}
public class Type3
{
public string domain
{
get;
set;
}
public bool flagged
{
get;
set;
}
public string category
{
get;
set;
}
public bool saved
{
get;
set;
}
public string id
{
get;
set;
}
public double created
{
get;
set;
}
}
This test passes:
[Test]
public void RoundTrip()
{
var response = new Response
{
schema = "Listing",
data = new ListingData
{
key = "28ba648c-de24-45d4-a7d9-70f810cf5438",
children = new List<object>
{
new Type1
{
body = "Four score and seven years ago...",
parent_id = "2qh3l",
report_count = 0,
name = "c4j6yeh"
},
new Type3
{
domain = "abc.def.com",
flagged = true,
category = "news",
saved = false,
id = "t3dz0",
created = 1335998011.0
}
}
}
};
var jsonSerializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Objects
};
string serializedResponse = JsonConvert.SerializeObject(response, jsonSerializerSettings);
Console.WriteLine(serializedResponse);
var roundTrippedResponse = JsonConvert.DeserializeObject<Response>(serializedResponse, jsonSerializerSettings);
Assert.That(roundTrippedResponse.data.children.First().GetType(), Is.EqualTo(typeof(Type1)));
Assert.That(roundTrippedResponse.data.children.Last().GetType(), Is.EqualTo(typeof(Type3)));
}
The output written to the console is:
{
"$type": "Test.Response, Test",
"schema": "Listing",
"data": {
"$type": "Test.ListingData, Test",
"key": "28ba648c-de24-45d4-a7d9-70f810cf5438",
"children": [
{
"$type": "Test.Type1, Test",
"body": "Four score and seven years ago...",
"parent_id": "2qh3l",
"report_count": 0,
"name": "c4j6yeh"
},
{
"$type": "Test.Type3, Test",
"domain": "abc.def.com",
"flagged": true,
"category": "news",
"saved": false,
"id": "t3dz0",
"created": 1335998011.0
}
]
}
}
So if you can transform your received response to match that of Json.NET's expected format, this will work.
To piece all of this together, you would need to write a custom MediaTypeFormatter and pass it to the ReadAsAsync<>() call.

Categories

Resources