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
Related
My goal is to get the data from the database, serializing them into JSON format and send it to the API. The problem is that I don't know how to get right JSON format for the API.
C# Worker service collecting data from database.
from database i got:
1|John|Wick|Action|101
my API needs this JSON:
{
"Name":"John",
"Surname":"Wick",
"Type":"Action",
"Length":"101"
}
when i use in C# serializing to JSON:
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(values);
i got:
[John,Wick,Action,101]
is there any way how to add name of values to JSON ?
First split the database result based on the delimiter
string dbResult = ...; //1|John|Wick|Action|101
string[] dbResults = dbResult.Split("|");
Second create an anonymous object (if you don't want to introduce a data model class/struct/record)
var result = new
{
Name = dbResults[0],
Surname = dbResults[1],
Type = dbResults[2],
Length = dbResults[3],
};
Third serialize the anonymous object
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(result);
I am writing a script to make configuration of a client automated. I want to be able to read a json file, and add a line in the existing json.
I have got as far as to read the json file - however I need some help with the editing of the json file
var pathToJson = Path.Combine(#"C:\" + DownloadConfigFilelocation);
var r = new StreamReader(pathToJson);
var myJson = r.ReadToEnd();
I need to add the line
"pageTitle": "Base Client",
to the json file below
I need to add this under "name".
The simplest option is to treat it as JSON: add a property, not a line:
// Load the content of the file as a string
string json = File.ReadAllText(pathToJson);
// Parse the JSON to a Newtonsoft.Json.Linq.JObject
JObject obj = JObject.Parse(json);
// Add the property
obj["pageTitle"] = "Base Client";
// Convert back to a JSON string
string newJson = obj.ToString();
// Save the string back to the file
File.WriteAllText(pathToJson, newJson);
This requires the Newtonsoft.Json NuGet package (aka Json.NET).
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.
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);
}
I am using Newtonsoft JSON.NET to create a dynamic JSON object which looks fine, but is unrecognizable when I send it to a REST API. My best guess is there are new lines in the JSON string which is breaking the process the API uses to parse the data. Is there a way to ensure all new lines are removed from the JSON data I am sending?
dynamic MyPerson = new JObject();
MyPerson.username = "CodeMonkey";
MyPerson.first_name = "Monkey";
MyPerson.last_name = "banana";
MyPerson.email_address = "bananacrazy#monkey.com";
MyPerson.is_active = true;
string PersonData = JsonConvert.SerializeObject(MyPerson);
The JSON it is returning if I use Response.Write is:
{"username":"CodeMonkey","first_name":"Monkey","last_name":"Banana","email_address":"monkey#bananacrazy.com","is_active":true}