SimpleJson in WP8 - c#

I am trying to parse a json file in WP8. For the moment I just need to get a list of topics with some titles each one. Something like:
[
{"topic":"topic1",
"titles":[{"title":"tit1"},
{"title":"tit2"},
{"title":"tit3"}]},
{"topic":"topic1",
"titles":[{"title":"tit1"},
{"title":"tit2"},
{"title":"tit3"}]}
]
My idea is get each topic and save in an array of 2 dimensions. In topic[X][0] would go topic and topic[x][y] the titles...
I have found this topic: Deserializing JSON using JSon.NET with dynamic data
In which is explained a bit how to do it but I am not able to get any of my data because the structure of the json is not similar. Any idea of how to do in this case?

To parse just call:
JArray json = JsonConvert.DeserializeObject(jsonText) as JArray;
For getting the topics just access it normally:
JObject arrayItem = json[0] as JObject;
Getting the topic and it's value:
JValue topic = arrayItem["topic"] as JValue;
string topicValue = topic.Value.ToString();
Getting the titles:
JArray titles = ArrayItem["titles"] as JArray;
And getting their values:
foreach (JObject jo in titles)
{
JValue title = jo["title"] as JValue;
string titleValue = title.Value.ToString();
}

Related

insert data into existing JSON Array in C#

I need to add some more data into existing JSON
eg:
{
"OrderId":"abc",
"products":["a","b","c","etc"]
}
how to add more into products
The approach would be similar to used in answer to your previous question, but you will need to convert element to JArray:
var x = #"{
'OrderId':'abc',
'products':['a','b','c','etc']
}";
var jObj = JObject.Parse(x);
((JArray)jObj["products"]).Add("new");
Try this:
var jObject = JObject.Parse(json);
var jArray = jObject["products"] as JArray;
jArray?.Add("new_product");

Cannot Parse JSON in UWP

I created an application on UWP whose data is parsed to JSON with JSON as below:
JSON
I'm having trouble parsing json on "jawaban" and an error message appears like below:
Code:
JsonArray jsonDataOption = groupObjectSoal["jawaban"].GetArray();
foreach (JsonValue groupValueOption in jsonDataSoal)
{
JsonObject groupObjectOption = groupValueSoal.GetObject();
string oid = groupObjectOption["oid"].GetString();
string option = groupObjectOption["q_option"].GetString();
string score = groupObjectOption["score"].GetString();
QuizOption pilihan = new QuizOption();
pilihan.OID = oid;
pilihan.Option = option;
pilihan.Score = score;
}
How to handle it?
Note:
For the full code, can be seen here
Property "list_soal" contains an array with two elements. The first element does not have property "jawaban", so your code fails on parsing first element
Use JSON.net
Newtonsoft
There are plenty examples on the site.
It will automatically fill your data model.
You can deserialize to object by calling.
YourObject m = JsonConvert.DeserializeObject<YourObject>(json);
where json is your json string and YourObject is your model

Check if user is on list

I have Array in JSON file. File looks like this:
["Maverick", "rick", "Rick", "prick", "rick_07"]
I have a username. I want to check if this username is in Array.
public string UserToCheck = "rick";
So im reading json file from URL...
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString("http://example.ex/users.json");
// Here I want to check if user is on list
}
}
But how Can I check if "UserToCheck" exactly match one of users from array?
You could parse your Json with the great Newtonsoft Json Library:
var users = JsonConvert.DeserializeObject<List<string>>(json);
users.Contains(UserToCheck);
As this is case sensitive, you could use LINQ: users.Any(u => String.Equals(u, UserToCheck, StringComparison.OrdinalIgnoreCase))
Trying parsing the object using JSON parsing. This requires placing the JSON string object into JSON.Parse method.
This portion may be missing:
JObject jObj = JObject.Parse(json);
Console.WriteLine(jObj);
Helpful links: http://www.newtonsoft.com/json/help/html/ParseJsonObject.htm
http://masnun.com/2011/07/08/quick-json-parsing-with-c-sharp.html
To check the string for names, break the names up into a list with C# and iterate through that to check the results.

c# iterate through json

Currently I am working on a soundcloud downloader in C#. With the help of the SoundCloud API I get a JSON string of a playlist, which includes a lot of information of the tracks:
http://pastebin.com/HfrjqyJE
I tried it with:
JObject results = JObject.Parse(e.Result);
foreach (var result in results["tracks"])
{
string streamUrl = (string)result["stream_url"];
string title = (string)result["title"];
}
it worked but it needs about 20 secs to iterate through a playlist with only 2 tracks. Is there a way to make this iteration process faster?
You could try using Newtonsoft JSON Deserializer.
For your case you could do something like this:
Create a Track class with needed properties
Apply DeserializeObject
Track jsonObject = JsonConvert.DeserializeObject<Track >(json);
Iterate over jsonObject
Perhaps looping over the properties using JProperty, performs better?
string json = "{a: 10, b: 'aaaaaa', c: 1502}";
JObject parsedJson = JObject.Parse(json);
foreach (JProperty property in parsedJson.Properties())
{
Console.WriteLine(string.Format("Name: [{0}], Value: [{1}].", property.Name, property.Value));
}

How to list a newtonsoft Jtoken or JObjects children in a listBox

I have a json file that i read to string and then convert to a jobject. I get a JToken from this object by selecting one of its children.
I want to list this JTokens children in a Listbox. I think, to do this i need to convert th eJTOken to a ListItem - how can i do this? If there is a better alternative way then would be interested to hear it!
string filePath = #"C:\output.json";
JObject json = JObject.Parse(System.IO.File.ReadAllText(filePath));
JToken jsonFiles = json["Files"];
jsonFilesListItem = ....
JsonListBox.Items.Add(jsonFilesListItem);
Assuming that json["Files"] contains a simple array of strings, all you have to do is use a foreach loop, as shown in the example below:
string jsonString = #"
{
""Files"": [
""foo.xml"",
""bar.txt"",
""baz.jpg"",
""quux.wav""
]
}";
JObject json = JObject.Parse(jsonString);
JToken jsonFiles = json["Files"];
foreach (string fileName in jsonFiles)
{
JsonListBox.Items.Add(fileName);
}

Categories