I have a json object and I want to get the value of :
entities > media > sizes > large > h
Is there a way to get it like XML -> Xpath method?
This is extra lines that is irrelevant to question just because of ...
{
"created_at": "Sun, 01 Jan 2012 17:05:32 +0000",
"entities": {
"user_mentions": [
{
"screen_name": "nurdanterbiyik",
"name": "nurdan",
"id": 264782080,
"id_str": "264782080",
"indices": [
0,
15
]
}
],
"media": [
{
"id": 153522253777219584,
"id_str": "153522253777219584",
"indices": [
44,
64
],
"media_url": "http://p.twimg.com/AiFrrSmCMAAdEID.jpg",
"media_url_https": "https://p.twimg.com/AiFrrSmCMAAdEID.jpg",
"url": "http://t.co/ZwHN9gvO",
"display_url": "pic.twitter.com/ZwHN9gvO",
"expanded_url": "http://twitter.com/emelkiraac/status/153522253773025280/photo/1",
"type": "photo",
"sizes": {
"large": {
"w": 536,
"h": 800,
"resize": "fit"
},
Using JSON.NET you have several ways to read data without having to deserialize your JSON text into objects. Here is a simplified example:
string json = #" {
""created_at"": ""Sun, 01 Jan 2012 17:05:32 +0000"",
""entities"": {
""media"": [{
""type"": ""photo"",
""sizes"": {
""large"": {
""w"": 536,
""h"": 800,
""resize"": ""fit""
}
}
}]
}
}
";
JObject o = JObject.Parse(json);
int h = (int)o["entities"]["media"][0]["sizes"]["large"]["h"];
int h2 = (int)o.SelectToken("entities.media[0].sizes.large.h");
I prefer to think of JSON purely as serialized objects--the first and last thing I want to do with it is to de-serialize it into the objects that I then work with.
I can't tell you the best way to do it in c#, but I've had good luck using JSON.NET
JSON.NET will also let you (quote from website) "LINQ to JSON is good for situations where you are only interested in getting values from JSON, you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects. LINQ to JSON allows you to easily read, create and modify JSON in .NET.", which sounds like what you are trying to do. I've never tried it, but if all you're trying to do is get one piece of data out of that long string, then it sounds like a good alternative.
Related
The Json file I have got few bullet characters due to which it is not parsing. I tried different ways to replace the bullet characters but no success. Help please. Thanks.
Json file content is below
"items": [ { "type": 202, "path": "C\TestFile.json", "name": " • OptionA?" }]
I tried following with no success.
option 1:
System.IO.File.ReadAllText(#"C:\\Users\\xxx\\Files\\JsonTestFile.txt").Replace(#"\\u2022",string.Empty)
option 2:
System.Text.RegularExpressions.Regex.Replace(strFileContent, "[\\u2022,\\u2023,\\u25E6,\\u2043,\\u2219]\\s\\d", " ");
option 3: converted the file to UTF-8 in notepad++ and tried parsing but it still fails.
{"items": [ { "type": 202, "path": "C\TestFile.json", "name": " • OptionA?" }]}
Above is the correct json but it will not compile because of the value you have for "path".
You have to escape the backslash with another \.. Following deserializes correctly.
{ "items": [ { "type": 202, "path": "C:\\TestFile.json", "name": " • OptionA?" }] }
Console.WriteLine(JObject.Parse(json)["items"][0]["path"].ToString());
//prints
C:\\TestFile.Json
After a bunch of research I haven't been able to find any good ways to read a json file, store their values, then append a new object/array to it.
The JSON looks like
{
"Skywars": [
{
"Solo Normal": [
{
"000001": [
{
"Kills": 213,
"Deaths": 117
}
]
}
],
"Solo Insane": [
{
"000001": [
{
"Kills": 10790,
"Deaths": 7184
}
]
}
]
}
],"Bedwars": [
{
"Solo": [
{
"000001": [
{
"Kills": 0,
"Deaths": 0
}
]
}
],
"Duos": [
{
"000001": [
{
"Kills": 0,
"Deaths": 0
}
]
}
]
}
]
}
As an example, i am intending for it to go "Skywars.Solo Normal", "Skywars.Solo Insane", "Bedwars.Solo", "Bedwars.Duos" then append "000002" with new kills and deaths values.
For some reason, even after hours of searching, I can't find out how to read the kills and deaths (I've gotten close, using public Skywars[] Skywars { get;set; }. Problem is most of the examples are using JSON files that look like {"user":[{"id":1,"logins":0}]} with very little arrays & sub arrays.
To anyone who is kind enough to answer, please don't spoonfeed me code, explain how it would be done (would I need to create my own parser, etc), or if there are already any posts/links that answer my question (even though I failed to find how).
Notes -
"000001" and "000002" will be dynamic, so each time you start the program those values will be different. I just want to append after the last instance of stats saved.
Also sorry, I am still learning C# but know most of the basics and some more complex concepts, I've just never been good at storing data and using JSON. If you need anything to help else just add a comment and I'll add it.
Please see Json.NET's Modifying JSON.
This sample loads JSON, modifies JObject and JArray instances and then writes the JSON back out again.
Sample
string json = #"{
'channel': {
'title': 'Star Wars',
'link': 'http://www.starwars.com',
'description': 'Star Wars blog.',
'obsolete': 'Obsolete value',
'item': []
}
}";
JObject rss = JObject.Parse(json);
JObject channel = (JObject)rss["channel"];
channel["title"] = ((string)channel["title"]).ToUpper();
channel["description"] = ((string)channel["description"]).ToUpper();
channel.Property("obsolete").Remove();
channel.Property("description").AddAfterSelf(new JProperty("new", "New value"));
JArray item = (JArray)channel["item"];
item.Add("Item 1");
item.Add("Item 2");
Console.WriteLine(rss.ToString());
// {
// "channel": {
// "title": "STAR WARS",
// "link": "http://www.starwars.com",
// "description": "STAR WARS BLOG.",
// "new": "New value",
// "item": [
// "Item 1",
// "Item 2"
// ]
// }
// }
I'm pulling intents back from API.AI and parsing these to C# objects using Newtonsoft.Json in the following way:-
intentListModel = JsonConvert.DeserializeObject<List<IntentListModel>>(intentList);
intentList is a JSON string from the webrequest. However at Line 1, position 161, it fails. The bit of JSON concerned is:-
"contextIn": [
"Employed"
],
"events": [{
"name": "Occupation_DOB"
}],
NB: This is only part of the JSON, and the JSON opens and closes with [] as it is a list of JSON items.
specifically the opening { on events. I'm stumped, I've run it through a validator and I see valid JSON.
Could anyone suggest what I can try, or is there a setting somewhere for this? Or is the error message actually looking another area of the JSON string?
Thanks in advance!
UPDATE
Whole JSON sample posted
[
{
"id":"18b025c5-3567-49c1-a9e9-25583f9156ca",
"name":"IncomeProtection - Employed? - Occupation/DOB/Email",
"state":"LOADED",
"contextIn":[
"Employed"
],
"events":[
{
"name":"Occupation_DOB"
}
],
"parentId":"ad5f0007-c084-4615-93dd-6c82ca5e7602",
"parameters":[
{
"required":true,
"dataType":"#Occupation",
"name":"Occupation",
"value":"$Occupation",
"prompts":[
"Whatu0027s your Occupation?"
],
"isList":false
},
{
"required":true,
"dataType":"#sys.date",
"name":"date",
"value":"$date",
"prompts":[
"Whatu0027s your date of birth?"
],
"isList":false
}
],
"contextOut":[
{
"name":"OccupationDOB",
"parameters":{
},
"lifespan":1
}
],
"actions":[
"IncomeProtection:Occupation/DOB"
],
"priority":500000,
"fallbackIntent":false
}
]
This issue was down to one of the items from the API being returned in a list, but in the particular example I looked at, the API returned a list of 1 item. I misread the brackets and created a class property of type string instead of List<string>, hence the failure of code.
Hope this helps people in the future.
Sorry for the messy title, I'm not sure how I should explain it better.
The JSON string I have:
{
"Name that varies here": {
"id": 01,
"ArrayOfType": [{
"name": "a name",
"id": 01
},
{
"name": "a name",
"id": 02
}]
},
"Another name": {
"id": 02,
"ArrayOfSameType": [{
"name": "a name",
"id": 03
},
....
I dont know how I should deserialize it, especially because the Object-name varies. Basically what I'd want is a List where someObject has String name, int ID and a List.
How should I create the object and deserialize it? So far I have only deserialized arrays/objects that are all called the same. I could make a class for each name (Name that varies here.cs, Another name.cs) with the variables and then deserialize it into that class.
I have some coordinates that I'm reading from a MongoDB using the 10Gen driver. The problem I'm running into is that the depth of the multi-dimensional data isn't consistent and I'm looking for a comprehensive strategy to handle the problem.
The solution must be able to write the coordinates back to MongoDB (serialize) in the same order and depth as read out (deserialized).
Two examples of different depth:
Example 1
[
[ [ [ 12, 33 ], [ 32, 23 ], [ 12, 32], [23, 12 ], [ 32, 32 ], [ 32, 2 ] ] ],
[ [ [35, 12 ], [ 53, 16 ], [ 22, 54 ], [ 2, 32 ], [ 32, 32 ] ] ]
]
Deserialize into:
public List<List<List<int>>> coordinates { get; set; }
Example 2
[
[ [ 2, 2 ], [120,12 ], [ 32,32 ], [ 32, 2 ], [ 3,2 ], [ 2, 3 ], [ 2, 1 ] ]
]
Deserialize into:
public List<List<List<List<int>>>> coordinates { get; set; }
My initial thought was to write a custom serializer to read the data and figure out the depth, then use a wrapper method to hide the actual data from the View e.g. GetNextCoordinate() and then the function GetNextCoordinate can pull the data from the appropriate structure. That feels messy so I'm looking for a more generic solution.
Assume that the coordinates property is part of a concrete class and that the collection in MongoDB contains a mix of both types of coordinate documents. Meaning any given query to MongoDB will pull either or both type of coordinate documents and I don't know before executing the query.
Maybe try http://www.codeproject.com/Articles/159450/fastJSON
It can serialize and deserialize to lists. I don't know if it can do lists within lists.
I ended up writing a custom BSON serializer/deserializer which then supports variable nested arrays.