Unity accessing JSON Object - c#

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;

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

Convert a JSON object/string to a C# dynamic object and have access to the properties/values?

I am trying to take a huge JSON file (could be a string) and without knowing the actual structure of the data I want to read and process it as a class in C#. I tried using JSON to deserialize it but I wasn't totally sure about where to go after that. I was thinking of using Reflections but not sure what data I need.
I have tried to deserialize the object as the code shows. But I want to test if it is the right object type incase it isn't I would hope it fails but I can't seem to get past this part. I also am not sure what to do with reflections inside of the check. I know I should iterate but not sure which property values inside of the object will contain what I need.
string jsonData = sr.ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(jsonData);
if (data is List<dynamic>)
{
data.GetType().GetProperties();
}
I want an object that has all the access to the data from a JSON file/string.
I think one of your problems is to use JArray instead of List and also you need to cast your item to JObject.
Use Newtonsoft.Json and Newtonsoft.Json.Linq then you can read your Json as an example:
string __content = "[ {\"name\": \"person1\" , \"age\": 33} , {\"name\": \"person2\" , \"age\" : 23} ]";
dynamic data = JsonConvert.DeserializeObject(__content);
// make sure you have an array of object
if (data is Newtonsoft.Json.Linq.JArray)
{
int i = 0;
foreach (dynamic item in data)
{
// get the property of the object
JObject currentitem = item as JObject;
if (currentitem != null)
{
// access to value of each property
foreach (JProperty p in currentitem.Properties())
{
Console.WriteLine("[" + i + "] : " + p.Name + ":" + p.Value.ToString());
}
i++;
}
}
}

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

ASP.NET getting indexed values when deserializing JSON into a dynamic object

So I have a JSON string that I am passing from an AJAX call to my controller. I have a list of indexed values that I am passing into a dynamic object.
I deserialize the JSON with
JsonConvert.DeserializeObject<dynamic>(s)
This is the output from that dynamic object:
"RolePermissions[0].RolePermissionId": "269",
"RolePermissions[0].HasAccess": "false",
"RolePermissions[1].RolePermissionId": "270",
"RolePermissions[1].HasAccess": "false",
"RolePermissions[2].RolePermissionId": "271",
"RolePermissions[2].HasAccess": "true",
"RolePermissions[3].RolePermissionId": "272",
"RolePermissions[3].HasAccess": "false"
When I try to access the a property of the object with
ssObj.RolePermissions[0].RolePermissionId
I get a RuntimeBinderException. I have tried to use JObject.Parse, which works great, but for some reason, the values in the array become out of order.
Any help would be greatly appreciated. Thanks!
When you try to do RolePermissions[0].RolePermissionId you are trying to access a nested collection containing an object with a property RolePermissionId at index 0. But your JSON doesn't represent a hierarchy of objects, it represents a single flat object with key/value pairs whose keys contain periods and brackets. Since c# identifiers don't allow such characters so you have no way to access such property values using dynamic directly.
Instead, your options include:
Take advantage of the fact that JsonConvert.DeserializeObject<dynamic>(s) actually returns a JObject and use its dictionary indexer:
var ssObj = JsonConvert.DeserializeObject<dynamic>(s);
var rolePermissionId = (string)ssObj["RolePermissions[0].RolePermissionId"];
If you prefer a slightly more typed solution, you could deserialize to a Dictionary<string, dynamic>:
var ssDict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(s);
var rolePermissionId = (string)ssDict["RolePermissions[0].RolePermissionId"];
Or for a much more statically typed solution, parse explicitly to a JObject and use LINQ to JSON:
var jObj = JObject.Parse(s);
var rolePermissionId = (string)jObj["RolePermissions[0].RolePermissionId"];
Sample fiddle showing the various options.
If you are in control of the data being sent via AJAX then make sure the data sent is properly formatted.
In order to be able to deserialize variable s like:
var ssObj = JsonConvert.DeserializeObject<dynamic>(s);
and access the resulting object in this manner:
ssObj.RolePermissions[0].RolePermissionId
then the JSON value in s, based on your sample and desired behavior, would have to look like this:
{
"RolePermissions": [
{
"RolePermissionId": "269",
"HasAccess": "false"
},
{
"RolePermissionId": "270",
"HasAccess": "false"
},
{
"RolePermissionId": "271",
"HasAccess": "true"
},
{
"RolePermissionId": "272",
"HasAccess": "false"
}
]
}
This quick unit test showed that it is possible to get indexed values when deserializing JSON into a dynamic object
[TestClass]
public class UnitTest1 {
[TestMethod]
public void GetIndexedValuesWhenDeserializingJSONIntoDynamicObject() {
var s = #"
{
'RolePermissions': [
{
'RolePermissionId': '269',
'HasAccess': 'false'
},
{
'RolePermissionId': '270',
'HasAccess': 'false'
},
{
'RolePermissionId': '271',
'HasAccess': 'true'
},
{
'RolePermissionId': '272',
'HasAccess': 'false'
}
]
}
";
var ssObj = JsonConvert.DeserializeObject<dynamic>(s);
var result = ssObj.RolePermissions[0].RolePermissionId;
Assert.AreEqual("269", (string)result);
}
}
So you need to make sure you are sending well formatted JSON to your controller to achieve desired behavior.

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