Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to set a variable from a jsonproperty that could have two different names?

Discussion in 'Scripting' started by ComeOnAndSam, Jun 14, 2023.

  1. ComeOnAndSam

    ComeOnAndSam

    Joined:
    Nov 8, 2016
    Posts:
    62
    I have a class with
    string id
    that is set from a JSON file. However, the potential JSON files that set this are not all standardized. In the json file, it could be labeled as "id" or "deviceid"

    So how can I set my "id" variable in both circumstances? I can only give it one json property.
     
  2. Zalosath

    Zalosath

    Joined:
    Sep 13, 2014
    Posts:
    671
    Just call JsonUtility.FromJson(json) to decode and then find either id or deviceid in the returned dictionary. Use a ternary operator if you want:
    Code (CSharp):
    1. string id = jsonDict.ContainsKey("id") ? jsonDict["id"] : jsonDict["deviceid"]
     
    Last edited: Jun 14, 2023
  3. ComeOnAndSam

    ComeOnAndSam

    Joined:
    Nov 8, 2016
    Posts:
    62
    I'm not sure how to use JsonUtility.FromJson to deserialize into a dictionary. What I did is

    Dictionary<string, string> jsonDict = JsonUtility.FromJson<Dictionary<string, string>>(json);


    which returns an empty dictionary
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,718
    JsonUtility does not support Dictionaries out of the box. Either serialize as a list of key/value structs, or use an alternate serializer such as Newtonsoft Json.