Aditya Patil
Aditya Patil

Reputation: 133

How to serialize and deserialize complex nested json Unity?

I have the following json

{
  "android_play_store_link": "xyz",
  "ios_app_store_link": "",
  "sticker_packs": [
    {
      "identifier": "1",
      "name": "abc",
      "publisher": "Jane Doe",
      "tray_image_file": "xyz.png",
      "image_data_version":"1",
      "avoid_cache":false,
      "publisher_email":"",
      "publisher_website": "",
      "privacy_policy_website": "",
      "license_agreement_website": "",
      "stickers": [
        {
          "image_file": "abc.webp",
          "emojis": ["☕","🙂"]
        },
        {
          "image_file": "cdf.webp",
          "emojis": ["😩","😰"]
        },
        {
          "image_file": "efg.webp",
          "emojis": ["☕","🙂"]
        }

      ]
    }
  ]
}

I have no acquaintance with json until now, How can i deserialize this ?

I know how to do the basic read and write code from persistent data path of unity. But how do i process this json ?

My main goal is as the player wins a level, a new key and value would be added to the "stickers" attribute, Also after some levels I want to add changes to the sticker packs attribute later.

Plus how will i modify the value of image data version in a specific sticker pack item ?

Thanks in advance

Upvotes: 2

Views: 497

Answers (1)

Vivek Nuna
Vivek Nuna

Reputation: 1

you can use Newtonsoft.Json library to deserialize and serialize. Find below the respective C# class.

public class Sticker
{
    public string image_file { get; set; }
    public IList<string> emojis { get; set; }
}

public class StickerPack
{
    public string identifier { get; set; }
    public string name { get; set; }
    public string publisher { get; set; }
    public string tray_image_file { get; set; }
    public string image_data_version { get; set; }
    public bool avoid_cache { get; set; }
    public string publisher_email { get; set; }
    public string publisher_website { get; set; }
    public string privacy_policy_website { get; set; }
    public string license_agreement_website { get; set; }
    public IList<Sticker> stickers { get; set; }
}

public class Root
{
    public string android_play_store_link { get; set; }
    public string ios_app_store_link { get; set; }
    public IList<StickerPack> sticker_packs { get; set; }
}

Code to Deserialize:

Root root = JsonConvert.DeserializeObject<Root>(json);

Upvotes: 3

Related Questions