Parsing JSON into list [duplicate] - c#

This question already has answers here:
Serialize and Deserialize Json and Json Array in Unity
(9 answers)
Closed 1 year ago.
So I was trying to parse the JSON data into list/array, but kinda stuck at the format like this.
I'm relatively new at JSON, so I'm not very good at processing those stuffs
Here's my code:
void processJsonData(string _url)
{
jsonDataClass jsnData = JsonUtility.FromJson<jsonDataClass>(_url); //_url is based on the Json text below
Debug.Log(jsnData.data);
}
I uses this code to see if it managed to get the data from it, but
it shows the error like this
The JSON looks like this:
[{"country":"Malaysia","sales":9244},
{"country":"Singapore","sales":3103},
{"country":"Japan","sales":1755},
{"country":"China","sales":7835},
{"country":"United States","sales":2755},
{"country":"United Kingdom","sales":8611},
{"country":"Australia","sales":3877}]
My jsonDataClass looks like this:
using System.Collections;
using System.Collections.Generic;
using System;
[Serializable]
public class jsonDataClass
{
public List<basicData> data;
}
[Serializable]
public class basicData
{
public string country;
public float sales;
}

Updated answer:
Apparently in Unity you can not directly deserialize collection/list/array with the built-in JsonUtility (thanks to #derHugo for the info), if you looking for quick and probably dirty solution, use below code:
List<basicData> jsnData = JsonUtility.FromJson<List<basicData>>("{\"data\":" + _url + "}");
And if you like to learn more, see: Serialize and Deserialize Json and Json Array in Unity and JSON Serialization

Related

Why is this JSON not being read correctly?

I have a large list of names in JSON arranged by country and sorted into male and female. I would like to be able to access these names within unity to apply them to various generated game characters etc. When trying to do this I am receiving a Null reference error but am out of ideas on how to approach/ fix it.
I have tried creating a Dictionary to access the names. Here is an example of the JSON:
//json example
{
"India":{
"male":[
"A_Jay",
"Aaban",
"Aabid",
"Aabir",
"Aadam"
],
"female":[
"A_Jay",
"Aaban",
"Aabid",
"Aabir",
"Aadam"
]
},
"Usa":{
"male":[
"A_Jay",
"Aaban",
"Aabid",
"Aabir",
"Aadam"
],
"female":[
"A_Jay",
"Aaban",
"Aabid",
"Aabir",
"Aadam"
]
}
}
Here is my attempt at reading the json file:
//jsonreader.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FirstName {
public List<string> male;
public List<string> female;
}
public class FirstNames {
public Dictionary<string, FirstName> countries;
}
public class JSONReader : MonoBehaviour {
public TextAsset jsonFile;
void Start(){
FirstNames firstNamesInJson = JsonUtility.FromJson<FirstNames>(jsonFile.text);
Debug.Log("Found name: " + firstNamesInJson.countries["India"].male[0]);
}
}
My Debug Log is returning a Null reference error and I'm not sure why.
Your root json element is a json object which does not have countries property so you don't need the "root" object FirstNames, use Dictionary<string, FirstName> directly:
var firstNamesInJson = JsonUtility.FromJson<Dictionary<string, FirstName>>(jsonFile.text);
P.S.
thanks to #derHugo in the comments - Unity built-in JsonUtility does not support the Dictionary deserialization ATM (docs), so you will need to use 3rd party library for such dynamic deserialization with Dictionary (for example Newtonsoft.Json)
Unity built-in JsonUtility uses the normal Unity serialization rules .. Dictionary is not supported by it... the main answer is:
You will need a third-party JSON library in the first place!
Like e.g. Newtonsoft JSON.Net (it comes as a package) and then as was mentioned before your JSON doesn't have a root.
see Deserialize a Dictionary
void Start(){
var firstNamesInJson = JsonConvert.DeserializeObject<Dictionary<string, FirstName>>(jsonFile.text);
Debug.Log("Found name: " + firstNamesInJson.countries["India"].male[0]);
}

How to parse Json files using Unity [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
In Unity (C#), why am I getting a NullReferenceException and how do I fix it? [duplicate]
(1 answer)
Closed 1 year ago.
Still on this issue, and I know this is an old post, but I'm also struggling to get C# to parse JSON.
I'm using Unity 2018.2.8f1, and VS 2019 (I also tried on VS 2017).
Here is my Json file (a really really simple one):
{
"glossary": {
"title": "example glossary"
}
}
And this is my C#:
using System;
using System.IO;
using UnityEngine;
[Serializable]
public class GlossaryRoot
{
public Glossary Glossary { get; set; }
}
[Serializable]
public class Glossary
{
public string title { get; set; }
}
public class Data_Manager : MonoBehaviour
{
private void Start()
{
string filePath = Path.Combine(Application.streamingAssetsPath, "Example.json");
string dataAsJSON = File.ReadAllText(filePath);
var myData = JsonUtility.FromJson<GlossaryRoot>(dataAsJSON);
string myTitle = myData.Glossary.title;
Debug.Log(myTitle);
}
}
I'm getting the error:
"NullReferenceException: Object reference not set to an instance of an object"
Any ideas on how to solve this issue? I've been looking for solutions, and tried a lot of things, but still with no success.
I know there are multiple issues similar to this one such as:
C#, Unity3D, JSON Parsing: Failing to parse JSON into C# object
But still I can't get it to work.
Even if I get delete the "gets and sets", I get "Null" in the console.
Any help is appreciated.
Thank you!
You names don't match it should be public Glossary glossary instead.
afaik Unity's Serializer (and therefore also the builtin JsonUtility) doesn't support (de)serialization of properties, rather use fields
so this should work
[Serializable]
public class GlossaryRoot
{
public Glossary glossary;
}
[Serializable]
public class Glossary
{
public string title;
}

JSON and VS C# objects and names [duplicate]

This question already has answers here:
How can I use a reserved keyword as an identifier in my JSON model class?
(3 answers)
Closed 2 years ago.
I need to serialize a JSON string containing the following:
{
commandId;
id;
params:
{
userId;
password;
}``
}
The code I was given uses Qt and they declare a QJsonObject paramsObj and a QJsonObject cmdObj;
they fill the field values and finally perform a cmdObj.insert("params", QJsonValue(paramsObj));
params is a keyword for VS and C# so I can't declare a class with that name, but this is the way the device will understand my JSON strings.
I am fairly new to JSON and looked at the .Net class and the Newtonsoft library but can't find how to perform the insert of a JSON object inside another, assigning an arbitrary name to it.
Can anyone shed some light?
Thank you.
You just need to escape params with # like this:
public class MyObject
{
public Params #params { get; set; }
}
This produces:
{
"params": {}
}
Or use Params as property name and use CamelCasePropertyNamesContractResolver.

JSON.NET serialization of type derived from List<T> [duplicate]

This question already has answers here:
How to serialize/deserialize a custom collection with additional properties using Json.Net
(6 answers)
How do I get json.net to serialize members of a class deriving from List<T>?
(3 answers)
Closed 5 years ago.
We're switching our cache system over from a binary serializer (the one AppFabric uses) to a JSON serializer (For use with Redis) and I'm running into some incompatibilities with a few object types. The general idea is the same, we have a class that looks something like this:
[Serializable]
public class ActivityMeasurementIndexes : List<ActivityMeasurementIndex>
{
public int Id { get; set; }
public DateTime lastDbRead { get; set; }
public ActivityMeasurementIndexes()
{
lastDbRead = DateTime.Now;
}
}
The binary serializer will serialize and deserialize the object just fine. However, when I try to serialize the object with JSON.NET, I get:
var testObject = new ActivityMeasurementIndexes { Id = 5 };
Newtonsoft.Json.JsonConvert.SerializeObject(testObject);
"[]"
So, JSON.NET is basically serializing the base List<T> but the properties in the derived type are getting lost. I could probably refactor this class so it has a public List<ActivityMeasurementIndex> Items { get; set } instead, but we have quite a few of these classes and tons of code that would also have to be refactored.
Is there a good approach to handle this? I don't really care how the JSON looks as long as I can serialize and deserialize the base list as well as the properties on the class. I'm guessing I would need to write some sort of custom converter, or maybe there's something JSON.NET can do out of the box to help me out. Any hints for stuff to read up on would be great!

Deserialization of JSON object by using DataContractJsonSerializer in C#

I'm sure this question has been asked over and over again, but for some reason, I still can't manage to get this to work.
I want to deserialize a JSON object that contains a single member; a string array:
[{"idTercero":"cod_Tercero"}]
This is the class that I'm trying to deserialize into:
[DataContract]
public class rptaOk
{
[DataMember]
public string idTercero { get; set; }
public rptaOk() { }
public rptaOk(string idTercero)
{
this.idTercero = idTercero;
}
}
This is the method that I try to deserialize:
public T Deserialise<T>(string json)
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
T result = (T)deserializer.ReadObject(stream);
return result;
}
}
And so I try to fill the object:
rptaOk deserializedRpta = deserializarOk(rpta);
But for some reason, this returns ""
MessageBox.Show(deserializedRpta.idTercero);
Without any dependencies outside of the .net framework, you could do it this way
[DataContract(Name="rptaOk")]
public class RptaOk
{
[DataMember(Name="idTercero")]
public string IdTercero { get; set; }
}
[CollectionDataContract(Name="rptaOkList")]
public class RptaOkList : List<RptaOk>{}
var stream = new StreamReader(yourJsonObjectInStreamFormat);
var serializer = new DataContractSerializer(typeof(RptaOkList));
var result = (RptOkList) serializer.ReadObject(stream);
I don't know if your're wiling to change the library that you're using, but I use library "Newtonsoft.Json" to desserialize JSON objects, it's pretty easy to use
[HttpPost]
public void AddSell(string sellList)
{
var sellList = JsonConvert.DeserializeObject<List<Sell>>(sellListJson);
BD.SaveSellList(sellList);
}
As you can see you can deserialize a whole json object list to a List<> fo the type "Sell", an object that i've created... And, of course, you can do that to an array too. I don't know the correct syntax for this, but you can convert this list to an array afterwards
Hope this helps
I think you're making this a lot more difficult than it needs to be. Firstly, your sample json and the class you're trying to deserialize into do not have an array of strings. They have a single property of type string. Secondly, why are you using this class DataContractJsonSerializer? You're not doing anything with it that you can't get from a simple call to json.NET's generic deserialization method. I would remove all of your code except the class definition and replace it with this simple one liner;
rptaOk[] myInstances = JsonConvert.DeserializeObject<rptaOk>(jsonString);
Also, no matter what the structure of your json is, if you have a class to correctly model it that method will correctly deserialize it. If you want to enforce some kind of contract I recommend using json schemas which json.NET also supports. If you use a schema it enforces a rigid contract, if you attempt to deserialize into an object there is something of an implicit contract. I don't know every scenario which will cause it to throw, but if your json is too far from the class definition it will. If your class has properties that don't appear in the json I believe they will just get initialized with the default values for that type.
EDIT: I just noticed your json is actually an array of objects. So you simply need to make the lhs of that assignment an array or rptaOk objects, rather than a singleton.

Categories