Parse Nested JSON with MiniJSON (Unity3D) - json

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

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

Insert json string to mongoDB

I am new to Scala and MongoDB. I am writing a Scala program to read JSON string (it can be nested json string also) and insert the same to Mongo DB.
I tried below few things but its not working.
1) Tried to create an Document for the JSON string as below:
var document = (DBObject) JSON.parse(jsonString)
but getting the error
"value JSON is not member of object com.mongodb.DBObject".
2) Also tried with bson.Document as below but still can get it working
var myDoc = (Document.parse(schemajson))
Can anyone help me out on this? Please let me know if my approach is correct. If not the please do let me know what all things I need to do.
adding code:
val hadoopRDD = sc.textFile(data_file).foreach(line =>
{
data_array.clear
line.split("\t").foreach(word => data_array += word)
println(data_array)
var final_json = (schemajson.format(data_array: _*))
var document = (DBObject) JSON.parse(jsonString)
in above code final_json is the string having Json string like {"name": xyz, "age": 22}
I found the answer and below is the solution which worked for me.
I was simply using
var document = (DBObject) JSON.parse(jsonString)
which was causing error.
Instead we need to provide asInstanceOf[DBObject] which worked in my case
val dbObject: DBObject = JSON.parse(final_json_str).asInstanceOf[DBObject]

Json.Parse returns same string that was passed, not creating an array of objects as expected

I've even saw that this has been posted before, but the answer seemed vague and didn't help me. Parsing the json string just returns a string and doesn't create an object with properties. I'm sure I'm missing something or haven't properly set this up. Any help would be greatly appreciated. Thanks in advance.
Json string being returned from web service:
[{"RctId":1,"Name":"Function Room 8 Hour Charge"},{"RctId":2,"Name":"Function Room 4 Hour Charge"}]
Code:
var obj;
var re = xmlhttp.responseText;
obj = JSON.parse(re);
document.getElementById("dp").innerHTML = obj;
alert(obj[0].RctId);
turns out I just needed to eval the reponsetext then it parsed just fine.

How to get the name of the token

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.

Concatenate JsonRepresentation

How can I concatenate multiple JsonRepresentation Object into one, without building my own string parser?
Say I have two JsonRepresentation objects
obj1 = {"name":"obj1"};
obj2 = {"name":"obj2"};
I would like to get the result concatenation as:
{
{"name":"obj1"},
{"name":"obj2"}
}
Reading the JsonRepresentation, there is no easy way to do this except by doing some string manipulation. Am I right?
Thanks
If you're referring to this JsonRepresentation class, and you want to merge the 2 objects into an array, then you should be able to do it as follows:
JSONObject jsonObj1 = obj1.toJsonObject();
JSONObject jsonObj2 = obj2.toJsonObject();
JSONArray jsonArray = new JSONArray().append(jsonObj1).append(jsonObj2);
JsonRepresentation jsonConcat = new JsonRepresentation(jsonArray);
Note: I haven't actually used the library, but if it behaves per the API, this should be pretty straightforward.