Json to array of objects C#
I have been searching for an answer to this question for a while and have come across many different solutions. However, it seems that Unity has recently implemented increased json capabilities so that third party solutions like litjson are not needed, plus I have not been able to get them to work. Usually I can scavenge forums for solutions but I am quite stuck.
I am receiving a json string of a mysql query via php and a json_encode of the resulting array, at least I believe it is a string. I want to convert the string into class created objects.
My json string is like this - {"kiva":[{"ProductID":"OBR","ProductName":"Organic Brown Rice","ProductPrice":"1.11"},{"ProductID":"OWR","ProductName":"Organic White Rice","ProductPrice":"2.22"},{"ProductID":"NBR","ProductName":"Non Organic Brown Rice","ProductPrice":"3.33"},{"ProductID":"NWR","ProductName":"Non Organic White Rice","ProductPrice":"4.44"}]}
I would like to auto fill an array of objects with each object being a product with the json listed ProductID, ProductName and ProductPrice. I feel like there are several failures in the code but this where I am at. My json is labled as the string productString.
[System.Serializable] public class groceryObject : MonoBehaviour {
[System.Serializable]
public class groceryI
{
public string ProductID;
public string ProductName;
public int ProductPrice;
}
public static string productString = jsonReturn.productString;
public groceryObject[] grocery = JsonUtility.FromJson<groceryObject>(jsonReturn.productString);
}
thank you
my json like this {"responseCode":1,"arrlstOurApps":[{"title":"Cricket Live Score & Schedule","desc":"Cricket Live Score & Schedule is the best app to get the updates of ipl on your Android mobile.\n
- Get all the time cricket live Updates, News, Schedule, Rankings.\n
- Including features like Scorecard, Full Scorecard, Point Table, $$anonymous$$ost Runs, $$anonymous$$ost Wickets, $$anonymous$$ost Hundreds, $$anonymous$$ost Fifties, $$anonymous$$ost Sixes, Past $$anonymous$$atches Statistics.","img_url":"https:\/\/lh3.googleusercontent.com\/GA-SDndYueiVw7pBG4r2SmV21VgvDDkVpTYbsJkWmbPXYrQ5grW44tcOnCWsji8PsA=w300","redirect_url":"https:\/\/play.google.com\/store\/apps\/details?id=softpulse.ipl2013"},{"title":"Gujarati Calendar 2018","desc":"Gujarati Calendar 2018 is Hindu traditional calendar app.\n
- Ti$$anonymous$$g of sunrise and sunset\n
- Days and Night Choghadiya\n
- And many more other functionality","img_url":"https:\/\/lh3.googleusercontent.com\/t8-p3uT7fZNE1XQqW9r4qVgZt0Aq$$anonymous$$dTZIUioJC62VuP4lCt7dXukYHvxi6moBXxAVw=s180","redirect_url":"https:\/\/play.google.com\/store\/apps\/details?id=com.softpulse.gujarati.calender"}]}
and my code like this
using UnityEngine; using System; using System.Collections; using UnityEngine.UI;
[System.Serializable] public class QrCodeResult { public QRCodeData [] result; }
[System.Serializable] public class Symbol { public int seq; public string data; public string error; }
[System.Serializable] public class QRCodeData { public string type; public Symbol [] symbol; }
public class JSON_Loader : $$anonymous$$onoBehaviour { public Text appName; public Text appDescription; public Text appUrl;
IEnumerator Request()
{
Debug.Log( "Requesting values" );
WWW www = new WWW( "http://softpulseinfotech.com/android/app_list.json" );
yield return www;
if (www.error != null)
{
print( "There was an error getting the data: " + www.error );
yield break;
}
string json = www.text;
var myObject = JsonUtility.FromJson<QrCodeResult>( "{\"result\":" + json + "}" );
Debug.Log("DATA : "+json);
if (myObject != null)
{
Debug.Log("ONE");
if (myObject.result != null)
{
Debug.Log( "TWO : " + myObject.result.Length );
if (myObject.result.Length> 0)
{
Debug.Log( "Val : " + myObject.result [0].type );
}
}
}
}
when i run the app it return error like Unexpected node type. UnityEngine.JsonUtility:FromJson(String) c__Iterator0:$$anonymous$$oveNext() (at Assets/Scripts/JSON_Loader.cs:46) UnityEngine.SetupCoroutine:Invoke$$anonymous$$oveNext(IEnumerator, IntPtr)
Answer by thegreatmiasma · May 24, 2016 at 05:37 PM
for those interested here is my currently working code. The foreach loop returns all the instances that should be held.
using UnityEngine; using System.Collections; using UnityEngine.UI; using System.Collections.Generic;
[System.Serializable] public class jsonReturn : MonoBehaviour { public Text returnProduct; public string json;
IEnumerator Start()
{
WWW product_get = new WWW ("www.bpschmidt.com/inputunity.php");
yield return product_get;
json = product_get.text;
returnProduct.text = product_get.text;
}
[System.Serializable]
public struct groceryObject
{
public string ProductID;
public string ProductName;
public int ProductPrice;
}
[System.Serializable]
public class groceryData
{
public List<groceryObject> kiva;
}
public void button()
{
groceryData data = JsonUtility.FromJson<groceryData>(json);
Debug.Log (data.kiva.Count);
Debug.Log (data.kiva [1]);
foreach (groceryObject tes in data.kiva) {
print (tes.ProductID + tes.ProductPrice + tes.ProductName);
}
}
}
Hi, I have a problem with extracting multiple objects data from the json string as well. I have created the json string and after processing it looks like this: << [{"FurnURL":"file:///C:/AssetsTest/cube","FurnName":"Cube(Clone)","FurnPos":{"x":2.4656989574432375,"y":0.5,"z":1.9058316946029664},"FurnRot":{"x":0.0,"y":-0.3402749001979828,"z":0.0,"w":-0.9403260946273804}},{"FurnURL":"file:///C:/AssetsTest/sphere","FurnName":"Sphere(Clone)","FurnPos":{"x":1.680193543434143,"y":0.5,"z":-0.797078013420105},"FurnRot":{"x":0.0,"y":0.3944152295589447,"z":0.0,"w":0.9189323782920837}}] >> When I try to use this with JsonUtility.FromJson, I get the error "ArgumentException: JSON must represent an object type." which implies that the root node of the JSON is not an object - since the JSON data must always be wrapped in { and }, you can't feed things like arrays directly to JsonUtility. So, I changed the resultant string to something similar to yours - i.e. I explicitly added << {\"furnys\": >> and << } >> at the beginning and the end of the string respectively. It doesn't show that error anymore but ins$$anonymous$$d I get a new one - "Object reference not set to an instance of an object" error. $$anonymous$$y load script looks like this : public class LoadScript : $$anonymous$$onoBehaviour {public static string json;public static void Load() {if(File.Exists("C:/AssetsTest/Saves/savedData.json")) json = File.ReadAllText ("C:/AssetsTest/Saves/savedData.json");FurnitureStats[] fs = JsonUtility.FromJson<FurnitureStats[]>(json);foreach (FurnitureStats furnn in fs) {print (furnn.FurnName);}}public void Loader() {Load ();}}
and my FurniStats Class looks like this :
using UnityEngine;using System.Collections;[System.Serializable]public class FurnitureStats {public string FurnURL;public string FurnName;public Vector3 FurnPos;public Quaternion FurnRot;}
EDIT: I am really sorry, I don't know how to format this here.
Could you help me with this? I am new to using Json as well as c#.
I'll look when I home but did you see my object is a struct not a class. That's switch made my json convert.
Yeah I did. Is that what's wrong? I found this while searching and they have a similar solution: http://forum.unity3d.com/threads/how-to-load-an-array-with-jsonutility.375735/ and they are using structs as well.
Yeah, if you look at superpig's reply half way down he or she has their object as a struct and not a class. I was getting an error, forget the specific error, but when I switched my object to a struct it worked. However, that was when I had all my scripting in one script. Now that I have my object created in a different script it is not sending this error. Is your FurniStats class inheriting $$anonymous$$onodevelop? I get your error if my object class is public class groceryObject : $$anonymous$$onoBehaviour but not public class groceryObject. It doesn't look like it but figured Id ask.
Your answer
Follow this Question
Related Questions
How to get an object (that is a prefab) from an array and instantiate it (C#) 1 Answer
JsonUtility and Arrays - JSON must represent an object type. 0 Answers
Problem with Json and Android ! 0 Answers
How to reliably send Kinect v2 data over MQTT? 1 Answer
JSON string to list with Simple JSON 0 Answers