How to get the name of the token - json

I need to parse json files which look as follows:
{"20120101":{"Jeff":{"Status":"Sleepy", "Weight":212}, "Cathy":{"Status":"Angry", "Weight":172}}
{"20120102":{"Jeff":{"Status":"Alert", "Weight":207}, "Cathy":{"Status":"Sick", "Weight":168}}
I cannot figure out a way to extract the dates (20120101 and 20120102) and names (Jeff and Cathy) from my json. My attempts look as follows:
private void LoadFile(string fileName)
{
var json = File.ReadAllText(fileName);
JObject days = JObject.Parse(json);
foreach (var dayAsObject in days)
{
var day = (JToken) dayAsObject;
var a = day.Root.ToString();
var t = day.ToString();
var z = day.First;
Console.WriteLine(day+t+z+a);
}

Better formulated json would look like
{"20120101":{ "name":"Jeff", "Status":"Sleepy", "Weight":212}, { "name":"Cathy", "Status":"Angry", "Weight":172}}
Then it is very easy to get day["name"]. I would suggest modifying your json. If you absolutely cant, I think the property you're looking for is PropertyName.
I tend to use the built in System.Web.Script.Serialization JSON libary. If you don't need to do fancy stuff it works great with the dynamic object type.

Related

LINQ on JArray always returning null

I'm trying to parse some Json in Xamarin.Forms
I'm pretty new to Xamarin, though not to .net
Here's my simple dimple code
var htc = new HttpClient();
var rsp = await htc.GetStringAsync("myurl.com");
JArray lists = JArray.Parse(rsp);
var c = lists.Count();
var l = lists.ToList();
var w=lists.Where(x => true);
Even though c returns the correct count of items in the list, l & w are both null
How come? and how do I fix it?
Thanks!
PS. What I'm really trying to do is bind a ListView to a JArray, but it seems impossible directly,(Text={Binding MyPropertyName} crashes the app). so I'm trying to run a Select on the JArray to convert to a KeyValuePair. If you have any ideas to bind directly, that would be best!
UPDATE
The issue seems even odder
I tried this
var kvlist = new List<KeyValuePair<string, string>>();
foreach (JObject ll in lists)
{
kvlist.Add(new KeyValuePair<string, string>(ll["Name"].ToString(), ll["Name"].ToString()));
}
Here at least the iteration works nicely, but the kvlist is null the entire time. Trying to evaluate the kvlist variable, I get:
Unable to cast object of type 'System.RuntimeType' to type
'Mono.Debugger.Soft.TypeMirror'.
What can the matter be?
Thanks again!
You should not directly call .ToList on object type of JArray rather you should Select List of type you need. For ex.
var l = lists.Select(c => new MyList
{
Item1 = c.Value<int>("ItemName1"),
Item2 = c.Value<string>("ItemName2")
}).ToList(); //Replce MyList with your class name
On the second case where w is null, after getting list l you need to specify attribute, based of what you are using where clause. For ex.
var w=l.Where(x =>x.isAdmin==true); //l is list you selected above
Hope it help you.
Solution:
You can use code below to convert a JArray to a list<T>:
List<T> t =lists.ToObject<List<T>>();
Refer: https://www.newtonsoft.com/json/help/html/ToObjectType.htm
You could also use JsonConvert.DeserializeObject to convert it directly into the desired type. You have to define a jsonModel class with the same structure of your json fisrtly.
List<jsonModel> modelList = JsonConvert.DeserializeObject<List<jsonModel>>(jsonStr);
Refer :https://www.newtonsoft.com/json/help/html/SerializingCollections.htm
The documentation seems to indicate that JArray has properties for .Count, but no overload method because it does not implement IEnumerable, however as alluded to in the comments, it does implement the JToken type (which JArray is a collection of) and implements IEnumerable.
See the following documentation for JToken: https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JToken.htm
and JArray respectively:
https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JArray.htm
The preferred mechanism is to create a strong type and then run .ToObject();
You can access JArray.ChildrenTokens which may help

JSON String parsing each character as an object

I have a JSON file that contains what I believe to be a correct JSON string:
{"title": "exampleTitle", "tipTitle": "exampleTipTitle", "tip": "exampleTip"}
I'm trying to parse said file and take out the 3 values then store them in variables, however currently, it parses each individual character as a separate object, therefore:
JSONobj[1] = "
and so on. Assuming that currentLocation = the directory location of the json file.
Code
var jsonLocation = currentLocation + "json.txt";
var request = new XMLHttpRequest();
request.open("GET", jsonLocation, false);
request.send(null);
var returnValue = request.responseText;
var JSONobj = JSON.parse(JSON.stringify(returnValue));
var headerTitle = JSONobj[0];
A few clarifications, the stringify is in because it was throwing an unexpected token error. I've tried changing the file tile to .json instead but that also makes no difference. "It also gives off a XMLHttpRequest on the main thread is deprecated" but I'm not particularly sure how to solve that issue. Any help would be appreciated.
var returnValue = request.responseText;
Here returnValue is a string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
var JSONobj = JSON.parse(JSON.stringify(returnValue));
Here you convert the string of JSON to JSON. So you have a JSON string representing a string, and that string is a representation of a data structure in JSON.
"\"{\\"title\\": \\"exampleTitle\\", \\"tipTitle\\": \\"exampleTipTitle\\", \\"tip\\": \\"exampleTip\\"}"
Then you parse it and convert it back to the original string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
So you end up back where you start.
Just don't use JSON.stringify here, and you'll convert your JSON to a JavaScript object:
var javascript_object = JSON.parse(returnValue);
Then you have an object, but it doesn't have a 0 property so it doesn't make sense to access it with javascript_object[0]. The properties have names, such as javascript_object.title.
Your JSON doesn't describe an array, so indexing into it with an index like 0 doesn't make sense. Your JSON describes an object, which will have properties with the names title, tipTitle, and tip.
Additionally, you're overdoing your parsing: You just want to parse, not stringify (which is the opposite of parsing):
var JSONobj = JSON.parse(returnValue);
So:
var JSONobj = JSON.parse(returnValue);
var headerTitle = JSONobj.title;
console.log(headerTitle); // "exampleTitle"
Side note: By the time you've assigned it to the variable you've called JSONobj, it isn't JSON anymore, it's just a normal JavaScript object, so that name is a bit misleading. If you're writing source code, and you're not dealing with a string, you're not dealing with JSON anymore. :-)

How to format a json string and show result in table?

I am using CakePhp _serialize method to make a web service and show the data in JSON format.I used the .json extension at the end of the URL to show this data.Now i want to show this data in table.Output image is attached.Is this possible then how i can do it?
Thanks
The format is a bit odd. I would prefer something like: "task_list": [ .... ]; iterating over objects is always a bit tedious.
Here is the jQuery code:
var data = ...;
var items = data["task_list"];
var table = $('<table/>');
table.appendTo($('body'));
$.each(items, function(id, value) {
var tr = $('<tr/>');
table.append(tr);
$('<td/>').text(id).appendTo(tr);
$('<td/>').text(value).appendTo(tr);
});

Parse Nested JSON with MiniJSON (Unity3D)

i'm very newbie with JSON so i'm having problems with nested JSON's.
I was searching two days without any luck, i saw a lot of examples of how to deserialize a nested JSON but my efforts failed so at last chance i'm here.
The thing i want to know is how i deserialize nested class with MiniJson, the JSONString is a facebook one, but i want to know the method for do it.
Here is an example of the JSONString i'm trying to deserialize.
{"data":
[{"user":{"name":"xxxxxxxxx1","id":"xxxxxxxxxx2"},"score":7,
"application":
{"name":"APPNAME","namespace":"APPNAMESPACE","id":"xxxxxxxxxx3"}}]}
Thanks in advance...
I tried with a lot of things this one is the last attempt i did, not a lot good but i was trying like a crazy to do it:
object dataObject;
object scoreObject;
var dict = Json.Deserialize(response.Text) as Dictionary<string,object>;
Debug.Log(response.Text);
var scores = new List<object>();
if(dict.TryGetValue ("data", out scoreObject)) {
Debug.Log("Hi");
scores = (string)(((Dictionary<string, object>)scoreObject) ["score"]);
if(scores.Count > 0) {
var scoreDict = ((Dictionary<string,object>)(scores[0]));
var score = new Dictionary<string, string>();
score["score"] = (string)scoreDict["score"];
Debug.Log((string)scoreDict["score"]);
}
}
PD: Sorry if my question is very noob or if i have a lot of negatives but it's really my last chance to understand something, thanks again.
Your problem lies in the fact that data contains an array and not an object, you need to get the first element of the data array and then get the value of score.
Something like this:
var dict = Json.Deserialize(response.Text) as Dictionary<string,object>;
List<object> scores = dict["data"] as List<object>;
Dictionary<string,object> scoreData = scores[0] as Dictionary<string,object>;
object score = scoreData["score"];

Parse json string that carries a collection of objects in actionscript using Json.parse

I am running into an error parsing a json string with JSON.parse(...)
var str:String= '[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3", "BB":"14"}]';
var propertySets:Object = JSON.parse(str);
I can tell that I am getting the syntax wrong with constructing the JSON string but I have tried quite a few things before giving up. Any help with how to deal with collections would be great.
The following simple case works for me
var str:String= '{"test":"line1"}';
var propertySets:Object = JSON.parse(str);
Thank you
The syntax in the JSON string is correct. The way it is formatted will return an Array instance from JSON.parse(). The following code works for me:
var str:String = '[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3", "BB":"14"}]';
var propertySets:Array = JSON.parse(str) as Array;
trace(propertySets[0].AA); // prints "A1"
trace(propertySets[0].BB); // prints "32"
Shot in the dark since I don't know actionscript, but try wrapping the array in an object
var str:String= '{"objectArray":[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3","BB":"14"}]}';