Search Unity

  1. Unity 2020.2 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

How parse Json data in Unity in C#?

Discussion in 'Scripting' started by 8Observer8, Feb 3, 2016.

  1. 8Observer8

    8Observer8

    Joined:
    Apr 29, 2015
    Posts:
    99
    Hi,

    How parse this Json-data in C#?
     

    Attached Files:

    hamidaminirad5 likes this.
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    7,367
    parse it into what?

    Unity has built in serializing objects into json and back out. But requires an object type to be defined for the serializing to and from:
    http://docs.unity3d.com/ScriptReference/JsonUtility.html

    Where as you can parse to and from a nesting table of key value pairs (dictionary for instance), because really that's all json is. And there are various tools out there available to do that.
     
    8Observer8 likes this.
  3. 8Observer8

    8Observer8

    Joined:
    Apr 29, 2015
    Posts:
    99
    I want to write, for example:
    string photo_75 = obj.photo75;

    Yes, I saw JsonUtility, but I don't know how use it because I need to get photo_75 from 'items' array.
     
    hamidaminirad5 and ZeShmoutt like this.
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    7,367
    You need to define an class that mirrors the json by name and type.

    I couldn't exactly show you what that class would look like because for some reason you posted the json as an image... use code tags please. I can't read one long string of random characters without any proper formatting.

    If you want examples unrelated to your specific json... well the documentation has it!

    http://docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html
     
    8Observer8 likes this.
  5. 8Observer8

    8Observer8

    Joined:
    Apr 29, 2015
    Posts:
    99
  6. 8Observer8

    8Observer8

    Joined:
    Apr 29, 2015
    Posts:
    99
    I found very interesting tool in Visual Studio. If select Json data and select in menu --> "Edit" --> "Paste Special" --> "Paste JSON as Classes" it will be generate this code below:

    Can I use it with JsonUtility?


    Code (CSharp):
    1. public class Rootobject
    2. {
    3.     public int count { get; set; }
    4.     public Item[] items { get; set; }
    5. }
    6.  
    7. public class Item
    8. {
    9.     public int id { get; set; }
    10.     public int album_id { get; set; }
    11.     public int owner_id { get; set; }
    12.     public string photo_75 { get; set; }
    13.     public string photo_130 { get; set; }
    14.     public string photo_604 { get; set; }
    15.     public int width { get; set; }
    16.     public int height { get; set; }
    17.     public string text { get; set; }
    18.     public int date { get; set; }
    19.     public int post_id { get; set; }
    20. }
    21.  
     
  7. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    7,367
    Ummm... honestly haven't used JsonUtility, but I know it uses the unity serialization engine. And unity serialization doesn't respect properties, and only fields.

    You may have to remove all the 'get/set' parts, making them raw fields.
     
    8Observer8 likes this.
  8. 8Observer8

    8Observer8

    Joined:
    Apr 29, 2015
    Posts:
    99
    I create class PhotoData:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class PhotoData
    5. {
    6.     public int count;
    7.     public Item[] items;
    8.  
    9.     public static PhotoData CreateFromJSON(string jsonString)
    10.     {
    11.         return JsonUtility.FromJson<PhotoData>(jsonString);
    12.     }
    13. }
    14.  
    15. public class Item
    16. {
    17.     public int id;
    18.     public int album_id;
    19.     public int owner_id;
    20.     public string photo_75;
    21.     public string photo_130;
    22.     public string photo_604;
    23.     public int width;
    24.     public int height;
    25.     public string text;
    26.     public int date;
    27.     public int post_id;
    28. }
    29.  

    I ran this code:

    Code (CSharp):
    1.     void Start()
    2.     {
    3.         //GetPhotos();
    4.  
    5.         string jsonString = "{\"count\":1,\"items\":[{\"id\":396326171,\"album_id\":-6,\"owner_id\":311627231,\"photo_75\":\"http://cs633231.vk.me/v633231231/1096c/1XDEN8hAVNg.jpg\",\"photo_130\":\"http://cs633231.vk.me/v633231231/1096d/HS3JINU5oBo.jpg\",\"photo_604\":\"http://cs633231.vk.me/v633231231/1096e/kEwS-DEk7fg.jpg\",\"width\":500,\"height\":456,\"text\":\"\",\"date\":1453586265,\"post_id\":1}]}";
    6.  
    7.         PhotoData pd = PhotoData.CreateFromJSON(jsonString);
    8.         Debug.Log("count = " + pd.count);
    9.     }
    10.  
    I see in Console: count = 1

    But when I want to get pd.items.Length I see the error:

    On this line:

    Code (CSharp):
    1. Debug.Log("items.Length = " + pd.items.Length);
     
  9. 8Observer8

    8Observer8

    Joined:
    Apr 29, 2015
    Posts:
    99
    I found the mistake :)

    I forgot to write [Serializable]

    Code (CSharp):
    1. using System;
    2.  
    3. [Serializable]
    4. public class PhotoData
    5. {
    6.     // ...
    7. }
    8.  
    9. [Serializable]
    10. public class Item
    11. {
    12.     // ...
    13. }

    Now I can write:

    Code (CSharp):
    1. Debug.Log("pd.items[0].photo_604 = " + pd.items[0].photo_604);
    And I see:

     
    Last edited: Feb 4, 2016
  10. g1zm0

    g1zm0

    Joined:
    Jun 14, 2017
    Posts:
    15
    How did y
    How did you split the json string into an array of objects. Doesn't that method only one for on objects so if you say:

    Code (CSharp):
    1.  PhotoData pd = PhotoData.CreateFromJSON(jsonString);

    you get on object from the json string, but then what if the json string contains several objects, how do you then iterate through it to get an array of these objects.

    P.S I was using:

    Code (CSharp):
    1. JsonData Objects= JsonMapper.ToObject(jsonstring);
    But it stopped working suddenly
     
    martejpad likes this.
  11. martejpad

    martejpad

    Joined:
    May 24, 2015
    Posts:
    23
    Hi @g1zm0, did you find a solution for splitting the json string into an array of objects? Any help would be greatly appreciated!

    Thanks a lot!
     
  12. altafkhan1002

    altafkhan1002

    Joined:
    Jun 20, 2018
    Posts:
    1
    Hope till now your problem get solved.
     
  13. damir2076

    damir2076

    Joined:
    Feb 13, 2018
    Posts:
    4
    I still dont understand. I am working with php and javascript and parsing json, xml or yaml last 10 maybe 15 years. But I cant understand how to parse in Unity big json like this one:
    {
    "submarines": [
    {
    "submarine_01": {
    "id": 1,
    "prefab": "submarine0",
    "price": 1000,
    "ini_submarine_speed": 15,
    "ini_torpedo_speed": 10,
    "ini_torpedoes": 2,
    "ini_reload": 10,
    "ini_damage": 10,
    "shop_submarine_speed": [
    {
    "id": 1,
    "price": 100,
    "value": 5
    },
    {
    "id": 2,
    "price": 300,
    "value": 7
    },

    and so on...Submarine_02 etc..

    Any help, I found only examples for very simple json objects which I dont understand why anybody put in json only 5-10 fields?!
     
  14. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,520
    Get a free JSON utility from the Unit Asset Store, and you'll be parsing JSON witin a few minutes.
     
  15. damir2076

    damir2076

    Joined:
    Feb 13, 2018
    Posts:
    4
    Thank you, first I was try JsonFormatter from BayatGames but it was not documented and hard to understand.

    Finnaly I found SimpleJSON yesterday.

    Here is a link to JSON parser:
    http://wiki.unity3d.com/index.php/SimpleJSON

    It was easy to implement in my case:
    using SimpleJSON;

    first load json file into string variable shop_json then:
    var n = JSON.Parse (shop_json);
    var submarine_list = n["submarines"][0]; // list of submarines
    or
    int submarine_id = n["submarines"][0]["submarine_01"]["id"]; // Id of submarine 1
     
    Bilgisoft likes this.
  16. ramkesh

    ramkesh

    Joined:
    May 15, 2019
    Posts:
    10
    I was also facing problem in json parsing in Unity. Now i have learnt to parse json by using both Newton Json plugin and json Utility class in Unity.
    For both way I used json2sharp site to create class of json. With Newton json Plugin you can use same class but with json Utility you have to made little change. First you have to remove set and get and just add ; with variables. and 2nd is you have to write [Serializable] on top of all class created by json2csharp. For reference you can follow my tutorial on it.
    Json Parsing in Unity by using Newton soft Plugin(.Net Json) and JsonUtility Class.
    First I have covered Newton json and then Json Utility class.Hope it will help you.
     
unityunity