Deserialize a json string in specific format - c#

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

Related

C# serializing JSON data from Database for API

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

JToken Array to Data Table C#

I have a JSON result with the following structure:
{
"property1":1,
"property2":[[1,"A"],[2,"B"],[3,"C"],...] // Possible to get >10000 values
}
Using the above JSON data format, I am only interested to get the array values from the property2 which contains an array of array values and convert it to data table.
The above JSON result is coming from an external WEB API and here is what I have currently:
var jsonResponse = API.RetrieveData();
JObject json = JObject.Parse(jsonResponse);
JToken[] A = json["property2"].ToArray();
Logically, I can loop on the elements of Array [] A column by column and add it to the predesigned data table. My problem is that, upon using this, the performance will be affected as in most cases, the data that will be retrieved from the API is > 10000 values.
Is there any specific way to convert this kind of JSON Format to DataTable in c# with the most efficient way?
Thank you in advance.
I have Better and Fast approach for You
Step 1
Create a class that is similar to json structure
public class JsonClass
{
public string property1 { get ; set; }
public List<Dictionary<int,string>> property2 { get ; set; }
}
Step 2
Use Newtonsoft and deserialize json input to json match class
JsonClass jsonClass = JsonConvert.DeserializeObject<JsonClass>(jsonInputString);
Step 3
if you are using WPF just use
datatable.ItemSource = jsonClass ;
if you are using Winform then use BindingSource Component
BindingSource binding = new BindingSource();
binding.DataSource = jsonClass;
datatable.DataSource = binding;
Result might be
property1 | property2
---------------------------------------
"A" | Collection
Good luck

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.

How to read the Json data without knowing the Key value

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;
}

Categories