Extract first element from JSON - c#

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.

Related

How to convert this json string to jobject

How to convert this json string to Jobject
"{\"user\":{\"id\":373697,\"username\":\"luckygirlxxx123\",\"counter_rechecking\":0,\"user_id\":76131,\"fb_id\":\"100047460285611\"}}";
I need it convert to Jobject like this because i need it to post data to website api . Example :
JObject concac = new JObject();
concac1["id"] = 373697;
concac1["username"] = "luckygirlxxx123";
concac1["counter_rechecking"] = 0;
concac1["user_id"] = 76131;
concac1["fb_id"] = "100047460285611";
Because It inside USER that i dont know how to create jobject with that
this code might help you.
public static void Main(string[] args)
{
string jsonData = "{\"user\":{\"id\":373697,\"username\":\"luckygirlxxx123\",\"counter_rechecking\":0,\"user_id\":76131,\"fb_id\":\"100047460285611\"}}";
var details = JObject.Parse(jsonData);
Console.WriteLine(string.Concat(details["user"]["id"], " " + details["user"]["username"]));
}
The simplest way is by giving those JSON values to the contracture of the object
public JObject(int id, string username, int user_id ....)
then you declare object and you pass values to it
JObject concac = new JObject(concac1["id"], concac1["username"], concac1["user_id"]..... );
The second way is JSON Serialization And Deserialization In C#

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

Newtonsoft Object serialized to String. JObject instance expected

Hi so am trying to parse this JSON line but i got some others that are like this in files thats why i want to automate this so i can remove the invalid lines to make the file a valid JSON for reading, The problem is that the JSON contains multiple JSON in 1 line
Example:
{"item":"value"}{"anotheritem":"value"}
Is there anyway to remove
{"anotheritem":"value"}
So it turns in to a valid JSON that is readable to start parsing the files
I tried doing using StreamReader cause there in a file i have multiple files that contain these invalid JSON
So i got it to be able to detect the Invalid JSON but for some reason i can't get it to read the JSON so i can use .remove to remove the invalid line
using (StreamReader r = new StreamReader(itemDir))
{
string json = r.ReadToEnd();
if (json.Contains("anotheritem"))
{
JObject NoGood = JObject.FromObject(json);
MessageBox.Show(NoGood.ToString());
}
}
The Error:
Object serialized to String. JObject instance expected.
Thank you all for your time and help.
If each object are side by side without space or any other character, you can convert your string to an json array.
string value = "{\"item\":\"value\"}{\"anotheritem\":\"value\"}";
string arrayValue = "[" + value.Replace("}{", "},{") + "]";
var array = JArray.Parse(arrayValue);
var goopArray = array.OfType<JObject>().Where(o => o.Property("anotheritem") == null);
Edit : see my second answer. More robust solution. More modern. And support dotnet core builtin json serializer.
Json.Net
Even better solution, Json.NET have a builtin feature for this exact scenario. See Read Multiple Fragments With JsonReader
The JsonTextReader have a property SupportMultipleContent that allow to read consecutive items when set to true
string value = "{\"item\":\"value\"}{\"anotheritem\":\"value\"}";
var reader = new JsonTextReader(new System.IO.StringReader(value));
reader.SupportMultipleContent = true;
var list = new List<JObject>();
while (reader.Read())
{
var item = JObject.Load(reader);
list.Add(item);
}
System.Text.Json
If you want to use System.Text.Json, it's also acheivable. They are no SupportMultipleContent property but Utf8JsonReader will do the job for you.
string value = "{\"item\":\"value\"}{\"anotheritem\":\"value\"}";
var bytes = Encoding.UTF8.GetBytes(value).AsSpan();
var list = new List<JsonDocument>();
while (bytes.Length != 0)
{
var reader = new Utf8JsonReader(bytes);
var item = JsonDocument.ParseValue(ref reader);
list.Add(item);
bytes = bytes.Slice((int) reader.BytesConsumed);
}

How can i access any key inside of json string via C#?

My question is simple but i can not do that. i wanna get value of "soap:Body" from below string by C#code?
{"soap:Envelope":{"xmlns:xsd":"http://www.w3.org/2001/XMLSchema","xmlns:soap":"http://www.w3.org/2003/05/soap-envelope","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","soap:Body":{"ToplamaResponse":{"xmlns":"http://tempuri.org/","ToplamaResult":156758}}}}
You can also use the Framework class JavaScriptSerializer if you do not want to use an external library.
string json = #"...";
JavaScriptSerializer serializer = new JavaScriptSerializer();
var o = serializer.Deserialize<dynamic>(json);
var body = o["soap:Envelope"]["soap:Body"];
You can do it easily by using Json.NET
dynamic data = JObject.Parse("{'soap:Envelope':{'xmlns:xsd':'http://www.w3.org/2001/XMLSchema','xmlns:soap':'http://www.w3.org/2003/05/soap-envelope','xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','soap:Body':{'ToplamaResponse':{'xmlns':'http://tempuri.org/','ToplamaResult':156758}}}}");
string soap_body = data["soap:Envelope"]["soap:Body"];
There is a simple example in the JObject.Parse documentation
string json = #"{
"soap:Envelope": {
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"xmlns:soap": "http://www.w3.org/2003/05/soap-envelope",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"soap:Body": {
"ToplamaResponse": {
"xmlns": "http://tempuri.org/",
"ToplamaResult": 156758
}
}
}
}";
JObject obj = JObject.Parse(json);
Console.WriteLine((string)obj["soap:Envelope"]["soap:Body"]);
And if you want to manipulate the value of "soap:Body" do the same thing :)

Categories