Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by thegreatmiasma · May 20, 2016 at 10:44 PM · c#arrayobjectsjson

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

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image softpulsedev13 · Feb 11, 2019 at 05:59 AM 0
Share

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)

1 Reply

· Add your reply
  • Sort: 
avatar image
5
Best Answer

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


}

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ImFromTheFuture · May 30, 2016 at 05:54 PM 0
Share

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#.

avatar image thegreatmiasma · May 30, 2016 at 06:10 PM 0
Share

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.

avatar image ImFromTheFuture thegreatmiasma · May 30, 2016 at 06:27 PM 0
Share

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.

avatar image thegreatmiasma ImFromTheFuture · May 31, 2016 at 04:55 PM 0
Share

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.

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

160 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges