C# serializing JSON data from Database for API - c#

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

Related

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

Unity accessing JSON Object

I am using Unity and Gamesparks. I am getting a Gamesparks object return but I am unable to access the data inside using C#.
private void OnScriptMessage(ScriptMessage message)
{
switch (message.ExtCode)
{
case "EndTurnMessage":
{
var data = message.Data;
string playerID = data.GetString("playerID");
print(message.JSONString);
break;
}
print(message.JSONString); displays
{"#class":".ScriptMessage","data":{"player":{"status":"win","choice":"scissors","newScore":1},"opponent":{"status":"lost","choice":"paper","newScore":0}},"extCode":"roundWonMessage","messageId":"5c74b1a8bcb1b604f0275ed5","notification":true,"playerId":"5c5b5823642c55481643846d","summary":"ScriptMessage"}
UnityEngine.MonoBehaviour:print(Object)
I wish to get newScore etc but I am confused with C# JSON
Your data is as follows:
"#class":".ScriptMessage","data":{"player":{"status":"win","choice":"scissors","newScore":1},"opponent":{"status":"lost","choice":"paper","newScore":0}},"extCode":"roundWonMessage","messageId":"5c74b1a8bcb1b604f0275ed5","notification":true,"playerId":"5c5b5823642c55481643846d","summary":"ScriptMessage"}
You need to deserialize it using ->
JsonUtility.FromJsonOverwrite(json, #class);
But to just get that one value you'd probably just need a good way of parsing your JSON. Under the base JSON root node is data, playerId, extCode, messageId, notification, summary. You need to treat the field "data" as a JSONObject and then both "player" and "opponent" as JSON Objects. Parse the value within it for
newScore.
Your data looks like this:
So your code would look something like this (this is to be used as a general guideline):
var data = message.Data;
string playerID = data.GetString("playerID");
var _data = data.GetObject("data"); //whatever to get data as JSON or Object
var _player = _data.GetObject("player"); //whatever to get data as JSON or Object
var _opponent= _data.GetObject("opponent"); //whatever to get data as JSON or Object
int _mscorePlayer = _player.GetInteger("newScore"); //Whatever the getter is for JSON Number it could be GetNumber or something comparable.
int _mscoreOpponent= _opponent.GetInteger("newScore"); //Whatever the getter is for JSON Number it could be GetNumber or something comparable.
print(message.JSONString);
print("your playerId:\t" + playerId);
print("your newScore:\t" + _mscorePlayer);
print("opponent newScore:\t" + _mscoreOpponent);
break;

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

Remove new lines in JSON string using Newtonsoft JSON.NET

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}

how to validate the json string in asp.net c#?

I have json string which will pass to the webservice to perform some action on it. My json string will b like this example:
{"ID":"2","Name":"Tom","data":"[22.3,23.4,21.5]"}
I want to validate the json string if I remove the , (coma):
{"ID":"2""Name":"Tom""data":"[22.3,23.4,21.5]"}
From the json string so its return error message json is not in the correct format.
JSON.net and JSONSharp allow you to parse JSON into an object and will have the ability to validate or at least catch an exception on errors
Try
var dynamicObject = Json.Decode(jsonString);
And see if it raises an error.
You may need to install the DLL for this separately. I believe it is in the MVC library download.
http://msdn.microsoft.com/en-us/library/system.web.helpers.json%28v=vs.111%29.aspx
Maybe you can try creating the JSON with the function ToJSON()
List<MyObject> people = new List<MyObject>{
new MyObject{ID = 1, Name= "Tom", Data= "[22.3,23.4,21.5]"},
new Person{ID = 2, Name= "Tome", LastName = ""[22.3,23.4,21.5]"}
};
string jsonString = people.ToJSON();
And if you with have the string as JSON you can do something like:
JsonConvert.SerializeObject(jsonString ).Dump();
Or using the Networking JSON:
http://james.newtonking.com/json
A working code snippet
public bool isValidJSON(String json) {
try {
JToken token = JObject.Parse(json);
return true; 
}
catch(Exception ex){ 
return false;
} 
}
Source

Categories