1

I have a string variable that contains The following JSON in it.

[
    {
        "MeterLookup_TblRefID": 233,
        "NetworkLookup_TblRefID": 3,
        "Network_Name": "SS-43 SEWA SCADA (Command Center)",
        "Longitude": 55.403544,
        "Latitude": 25.366666,
        "OnOFfStatus": true
    },
    {
        "MeterLookup_TblRefID": 297,
        "NetworkLookup_TblRefID": 4,
        "Network_Name": "SS-8 MaySaloon",
        "Longitude": 55.406274,
        "Latitude": 25.360654,
        "OnOFfStatus": true
    },
    {
        "MeterLookup_TblRefID": 298,
        "NetworkLookup_TblRefID": 5,
        "Network_Name": "SS-1 Al Nasserya Driving School",
        "Longitude": 55.404669,
        "Latitude": 25.367591,
        "OnOFfStatus": true
    }
]   

I want to parse it to a JSON object in unity

. Anyone can please tell me how to do it.

Savad
  • 1,240
  • 3
  • 21
  • 50

2 Answers2

1

Use this function:

public static T[] DeserializeFromJsonArray<T>(string jsonString)
    {        
            string newJson = "{ \"array\": " + jsonString + "}";
            Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(newJson);
            return wrapper.array;        
    }

Like this:

JsonObjectModel[] arrayOfObjects = DeserializeFromJsonArray<JsonObjectModel>(jsonArrayString);

If you want to Serialize again, do it with:

public static string SerializeToJsonArray<T>(T[] arrayToSerialize)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.array = arrayToSerialize;
        return JsonUtility.ToJson(wrapper);
    }

And use it like this:

 string jsonString = JsonManager.SerializeToJson<JsonArrayModel>(jsonArrayModel);

If you have more questions, I got a repo with some UnityUtils that include an example of this JsonManaging here: https://github.com/EricBatlle/SimpleUnityUtils/tree/master/Assets/Simple_JsonManager

Lotan
  • 4,078
  • 1
  • 12
  • 30
0

You can use Unity's JSONUtility.

This example was taken from Unity's documentation itself.

using UnityEngine;

[System.Serializable]
public class PlayerInfo
{
    public string name;
    public int lives;
    public float health;

    public static PlayerInfo CreateFromJSON(string jsonString)
    {
        return JsonUtility.FromJson<PlayerInfo>(jsonString);
    }

    // Given JSON input:
    // {"name":"Dr Charles","lives":3,"health":0.8}
    // this example will return a PlayerInfo object with
    // name == "Dr Charles", lives == 3, and health == 0.8f.
}

Reference: https://docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html

Sergio Carneiro
  • 3,726
  • 4
  • 35
  • 51
  • In this case OP has an array for which Unity's JsonUtility actually is quite tricky to use. This question already has an answer in [Serialize and Deserialize Json and Json Array in Unity](https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity) – derHugo Mar 06 '20 at 06:20