I have a json data which comes as the input string. Now I need to update the existing Json data with the input Json data. In my case, I want to go through each key and match with existing Json data and then update the value of that Key with input Json data.
Code to retrive the existing data
var existingJSon = ProductRepository.ListOfProd.Cast<JArray>().Where(x => x["ProdId"].ToString() == id.ToString());
After retrieving the data my existingJson will look like below.
{
ProdId:"1",
Title:"C#",
Author:"Jeffy",
Publisher:"XYZ",
Category:"Microsoft"
}
Now I need to loop through every key that comes as the input and match to the existing Json key and update the value of that key.
Input and after updating it should look like this:
{
ProdId:"1",
Title:"C#",
Author:"Jeffy",
Publisher:"abcd",
Category:"Microsfot Basic .Net Development Kit"
}
See if this helps you, We can use Newtonsoft to deserialize unknown types and loop the keys and values.
string json = "{ProdId:\"1\",Title:\"C#\",Author:\"Jeffy\",Publisher:\"XYZ\",Category:\"Microsoft\"}";
JObject obj = JsonConvert.DeserializeObject < JObject>(json);
var properties = obj.Properties();
foreach (var prop in properties)
{
string key = prop.Name;
object value = prop.Value;
}
Related
I have two auto generated JSON data as shown below. I want to get all the data in Colors Tag.
I Created a JArray of "Colors" and started looping on all data available, but when there is only one color available my code starts giving exceptions as "Colors" is not a JArray instead a JProperty. See sample code below.
What is the ideal way of handling this situation?
{
"UID":1234,
"Colors":["red", "blue", "green"]
}
{
"UID":1234,
"Colors":"green"
}
JObject jsonObject = (JObject)JsonConvert.DeserializeObject(jsonText, settings);
foreach (JObject reg in jsonObject["Colors"]) {
// Write to console.
}
First I would let your schema JSON "Colors" be an array because that can let your JSON be a strong schema.
if you can't modify the schema You can try to use JObject.Parse then use is to judge the type
var jsonObject = JObject.Parse(jsonText);
if (jsonObject["Colors"] is JArray)
{
foreach (JObject reg in jsonObject["Colors"]) {
// Write to console.
}
}
else if(jsonObject["Colors"] is JToken)
{
//jsonObject["Colors"]
}
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 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
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.
I am trying to deserialize the JSON string below:
[{"Code1":"AA","Code2":"AB"},{"Code1":"BB","Code2":"BC"},
{"Code1":"A1","Code2":"A12"},{"Code1":"A2","Code2":"A23"},
{"Code1":"A4","Code2":"A45"},{"Code1":"A3","COde2":"A45"}]
into the following format:
{"Header":["Code1","Code2"], "Values":[["AA","AB"],["BB","BC"],["A1","A12"],["A2","A23"],["A4","A45"],["A3","A45"]]}
I am trying to deserialize using JsonConvert.DeseriaizeObject(). I am not able to achieve the desired format.
Ah, so you have a collection of identically structured objects, and want to convert it to something akin to a CSV table (sequence of headers, then sequence of records)?
You can convert from the objects collection format to records table format using the following method:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//other code, class declaration etc. goes here
string ObjectsToTable(string collectionJson)
{
// reading the collection from passed JSON string
JArray collection = JArray.Parse(collectionJson);
// retrieving header as a list of properties from the first element
// it is assumed all other elements have the exact same properties
List<string> header = (collection.First as JObject).Properties().Select(p => p.Name).ToList();
// retrieving values as lists of strings
// each string is corresponding to the property named in the header
List<List<string>> values = collection.Children<JObject>().Select( o => header.Select(p => o[p].ToString()).ToList() ).ToList();
// passing the table structure with the header and values
return JsonConvert.SerializeObject(new { Header = header, Values = values });
}