Newtonsoft.Json, How to code generic selection - c#

Further on with Newtonsoft.Json, Path returned multiple tokens,
For this code:
JObject o = JObject.Parse(jsStr);
IEnumerable<JToken> selEnum = o.SelectTokens(theFilter);
where the jsStr is the content of https://api.github.com/search/repositories?q=Newtonsoft.Json&sort=stars&order=desc, and theFilter can be any valid JPATH query string (e.g., ".items" or ".items[*].owner").
How to return the selected as a valid json string?

It sounds like you just need Json.SerializeObject:
var o = JObject.Parse(jsStr);
var selEnum = o.SelectTokens(theFilter);
var newJson = JsonConvert.SerializeObject(selEnum);
This will give you JSON representing an array of all of the owner values from the original JSON.

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

Extract first element from JSON

How can I take just the first element from a Json?
//take result back
void HandleIncomingMessage(object sender, PEventArgs e)
{
RetMessage += e.Result;
//here can not deserialize correct
var deserialized_message = JsonConvert.DeserializeObject<Message>(RetMessage);
}
Here I am doing the deserialize but because it`s taking the entire object can not parse it correct.
I need just JSON.[0]
Edit: Raw Json :
[{"unique_id":55,"action_name":"INSERT","start_date":"2018-06-11T16:00:00","end_date":"2018-06-11T17:00:00"},"1sddsd","my_channel"]
Deserialize to List<dynamic>, then read the properties of its first element.
//using Newtonsoft.Json;
var input = #"[{""unique_id"":55,""action_name"":""INSERT"",""start_date"":""2018-06-11T16:00:00"",""end_date"":""2018-06-11T17:00:00""},""1sddsd"",""my_channel""]";
var output = JsonConvert.DeserializeObject<List<dynamic>>(input);
Console.WriteLine(output[0].unique_id);
Output:
55
DotNetFiddle
How about getting json string and using JSON.net
//first create object from json
JObject jObject = JObject.Parse(jsonString);
//read unique value
string jUniqueId = jObject["unique_id"];
//or
string firstObject = jObject[0];
the solution is for static,
JObject obj= JObject.Parse(here pass the JSON);
string id= JSON[0]["unique_id"],
string name= JSON[0]["action_name"],
string sdate= JSON[0]["start_date"],
string edate= JSON[0]["end_date"]
dynamic means pass i instead of 0.

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

Add a Root Key for an Orphan JSON using C#

I need to add a Key for the Orphan JSON object
JSON String:
string jsonString = "{\"FirstName\":\"Emma\",\"LastName\":\"Watson\"}";
Expected JSON String:
string jsonString = "{\"PersonName\":{\"FirstName\":\"Emma\",\"LastName\":\"Watson\"}}";
I need to add a Key for the above said actual JSON string as like expected JSON using C#.
I tried the following code:
string rootKey = "PersonName";
string jsonString = "{\"FirstName\":\"Emma\",\"LastName\":\"Watson\"}";
var jObj = JObject.Parse(jsonString);
// Need to add a ROOT Key for this jObj...
Simillar to the existing question How to add a key to a JSON array value?
You're not adding a property to the object, you're putting the object in another object. Just think of it as a dictionary. Create a "dictionary" and add your object to it. Then you could get the json string back from that object.
var jsonString = "{\"FirstName\":\"Emma\",\"LastName\":\"Watson\"}";
var jsonObj = JObject.Parse(jsonString);
var newObj = new JObject
{
["PersonName"] = jsonObj,
};
var newJsonString = newObj.ToString();

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.

Categories