Angelsm
Angelsm

Reputation: 329

Can't read a json data

I'm working in Unity and trying to read a Json data with LitJson. It works fine when I read the tournamentCode data but I don't get to read the "desc"{"en": "" } data. Can anybody help me?

This is the Json data:

{
  "data": {
    "server_time": 1554749832667,
    "leaderboardEnrollment": {
      "score": 12,
      "data": {
        "nickname": ""
      },
      "createdAt": 1554476229071,
      "updatedAt": 1554476302054,
      "tCode": "T8",
      "tRank": 1,
      "tClaimedAt": 0,
      "tNotifiedAt": 0
    },
    "versionId": 2,
    "tournamentTimetable": {
      "tRegistrationStart": 1554475800000,
      "tState": "COMPLETE",
      "tPlayEnd": 1554479100000,
      "tRegistrationEnd": 1554477300000,
      "tPlayStart": 1554475800000
    },
    "tournamentConfigs": [
      {
        "tournamentCode": "T8",
        "description": {
          "name": {
            "en": "TORNEO8"
          },
          "desc": {
            "en": ""
          }
        },
        "customJson": {},
        "payoutRules": [],
        "entryFee": {}
      }
    ],
    "enrolled": true
  },
  "status": 200
}

And this is my code:

public class BC_TData : MonoBehaviour
{
    public GameObject Button_Template;

    public string escena = "08_MenuInicio";
    private string ScorePlayerCH;

    private BrainCloudWrapper _bc;

    private readonly List<BC_PlayerInfo> lblist = new List<BC_PlayerInfo>();
    private readonly List<BC_PlayerInfo> tlist = new List<BC_PlayerInfo>();
    private readonly List<BC_PlayerInfo> dlist = new List<BC_PlayerInfo>();

    private int versionId = 2;

    public Text TituloTorneo;
    public Text FechaComienzoPartida;
    public Text FechaFinalizacionPartida;
    public Text FechaComienzoUnirse;
    public Text FechaFinalizacionUnirse;
    public Text DescripcionTorneo;
    public Text UnidoTorneo;

    public GameObject ventana1;
    public GameObject BotonUnirse;
    public GameObject BotonSeguir;


    void Start()
    {
        _bc = GameObject.Find("BConnect").GetComponent<BC_Connect>().GetBrainCloud();
        _bc.LeaderboardService.ListLeaderboards(ApiSuccess, ApiError);
    }

    private void ApiSuccess(string jsonResponse, object cbObject)
    {

        lblist.Clear();
        var leaderboardsList = JsonMapper.ToObject(jsonResponse)["data"]["leaderboardList"];
        foreach (JsonData leaderboardId in leaderboardsList) lblist.Add(new BC_PlayerInfo(leaderboardId));
        foreach (var leaderboardId in lblist)

        {
            string _leaderboardId = leaderboardId.LeaderboardId;
            Debug.Log(_leaderboardId);

            string _rotationType = leaderboardId.RotationType;
            Debug.Log(_rotationType);

            if (_rotationType == "ADHOC")
            {

                GameObject go = Instantiate(Button_Template) as GameObject;
                go.SetActive(true);
                BC_Tutorial_Button TB = go.GetComponent<BC_Tutorial_Button>();
                TB.SetName(_leaderboardId);
                go.transform.SetParent(Button_Template.transform.parent);
                go.transform.localScale = new Vector3(1, 1, 1);
            }
            else
            {
                Debug.Log("No es tabla asociada a un evento");
            }

        }
        Debug.Log("Listado de eventos enviado con éxito");
    }

    private void ApiError(int status, int reasonCode, string jsonError, object cbObject)
    {
        Debug.Log("Error al enviar el Listado de eventos");
    }

    public void ButtonClicked(string _leaderboardId)
    {

        ES2.Delete("ChallengeId.txt");
        ES2.Save(_leaderboardId, "ChallengeId.txt");
        Debug.Log(_leaderboardId + " button clicked.");

        _bc.TournamentService.GetTournamentStatus(_leaderboardId, versionId, successCallback, failureCallback);
    }

    private void successCallback(string jsonResponse, object cbObject)
    {
        var _tState = JsonMapper.ToObject(jsonResponse)["data"]["tournamentTimetable"]["tState"];
        var _tRegistrationStart = JsonMapper.ToObject(jsonResponse)["data"]["tournamentTimetable"]["tRegistrationStart"];
        var _tRegistrationEnd = JsonMapper.ToObject(jsonResponse)["data"]["tournamentTimetable"]["tRegistrationEnd"];
        var _tPlayStart = JsonMapper.ToObject(jsonResponse)["data"]["tournamentTimetable"]["tPlayStart"];
        var _tPlayEnd = JsonMapper.ToObject(jsonResponse)["data"]["tournamentTimetable"]["tPlayEnd"];
        var _tEnrolled = JsonMapper.ToObject(jsonResponse)["data"]["enrolled"];

        var __tState = _tState.ToString();
        var __tRegistrationStart = DateTimeOffset.FromUnixTimeMilliseconds((long)_tRegistrationStart).ToLocalTime().ToString("dd/MM/yyyy hh:mm tt");
        var __tRegistrationEnd = DateTimeOffset.FromUnixTimeMilliseconds((long)_tRegistrationEnd).ToLocalTime().ToString("dd/MM/yyyy hh:mm tt");
        var __tPlayStart = DateTimeOffset.FromUnixTimeMilliseconds((long)_tPlayStart).ToLocalTime().ToString("dd/MM/yyyy hh:mm tt");
        var __tPlayEnd = DateTimeOffset.FromUnixTimeMilliseconds((long)_tPlayEnd).ToLocalTime().ToString("dd/MM/yyyy hh:mm tt");
        var __tEnrolled = _tEnrolled.ToString();


        Debug.Log(__tEnrolled);
        Debug.Log(_tState);
        Debug.Log(__tPlayStart);
        Debug.Log(__tPlayEnd);
        Debug.Log(__tRegistrationStart);
        Debug.Log(__tRegistrationEnd);

        FechaComienzoPartida.text = __tPlayStart;
        FechaFinalizacionPartida.text = __tPlayEnd;
        FechaComienzoUnirse.text = __tRegistrationStart;
        FechaFinalizacionUnirse.text = __tRegistrationEnd;

        tlist.Clear();

        var tournamentsList = JsonMapper.ToObject(jsonResponse)["data"]["tournamentConfigs"];

        foreach (JsonData tournamentCode in tournamentsList) tlist.Add(new BC_PlayerInfo(tournamentCode));
        foreach (var tournamentCode in tlist)
        {
            string _tournamentCode = tournamentCode.TournamentCode;
            Debug.Log(_tournamentCode);
            TituloTorneo.text = _tournamentCode;
        }

        dlist.Clear();

        var descriptionsList = JsonMapper.ToObject(jsonResponse)["data"]["tournamentConfigs"];

        foreach (JsonData description in descriptionsList) dlist.Add(new BC_PlayerInfo(description));
        foreach (var description in dlist)
        {
            string _description = description.Description;
            Debug.Log(_description);
            DescripcionTorneo.text = _description;
        }

    }

    private void failureCallback(int status, int reasonCode, string jsonError, object cbObject)
    {
        Debug.Log("Error al listar Torneos");
    }
}

And this is the way I use with BC_PlayerInfo:

public BC_PlayerInfo(JsonData jsonData)
{
    PlayerName = SafeGet(jsonData, "playerName");

    if (PlayerName.Equals("")) PlayerName = SafeGet(jsonData, "name");
    Score = SafeGet(jsonData, "score");
    ProfileId = SafeGet(jsonData, "playerId");
    if (ProfileId.Equals("")) ProfileId = SafeGet(jsonData, "profileId");
    Rank = SafeGet(jsonData, "rank");
    PlayerRating = SafeGet(jsonData, "playerRating");
    LeaderboardId = SafeGet(jsonData, "leaderboardId");
    RotationType = SafeGet(jsonData, "rotationType");
    TournamentCode = SafeGet(jsonData, "tournamentCode");
    Description = SafeGet(jsonData["description"], "desc");
}

public BC_PlayerInfo()
{
}

private string SafeGet(JsonData jsonData, string key)
{
    var returnValue = "";
    try
    {
        returnValue = jsonData[key].ToString();
    }
    catch (Exception e)
    {
    }
    return returnValue;
}

Upvotes: 1

Views: 541

Answers (2)

derHugo
derHugo

Reputation: 90872

TournamentCode = SafeGet(jsonData, "tournamentCode");

works since

"tournamentCode": "T8"

from the JSON string is of type string.

Description = SafeGet(jsonData, "description");

however does not since

"description": { "name": { "en": "TORNEO8" }, "desc": { "en": "" } }

from the JSON string is a nested type (JsonData), not a string. So

jsonData[key].ToString();

will return the string JsonData object.


You can either go with this other answer and implement all classes represented by the JSON

or if this is too much overkill for you since you want only a certain field of the Json than you should get that specific field:

Description = SafeGet(jsonData["description"]["desc"], "en");

or you would need a wrapper method if you want this to be "safe" as well

private JsonData SafeGetSubData(JsonData jsonData, string key)
{
    try
    {
        return jsonData[key];
    }
    catch
    {
        return null;
    }
}

and then use it like e.g.

var descriptionData = SafeGetSubData(jsonData, "description");
var desc = descriptionData != null ? SafeGetSubData(descriptionData, "desc") : null;
Description = SafeGet(desc, "en");

due to the try-catch block this also works if desc was null.


Than like in my comment I didn't understand why you are using multiple lists and foreach loops when you always get the same content anyway ... you rather could do it all in one loop and only with one single list:

private readonly List<BC_PlayerInfo> playerInfoList = new List<BC_PlayerInfo>();

...

playerInfoList.Clear();

var tournamentConfigs = JsonMapper.ToObject(jsonResponse)["data"]["tournamentConfigs"];

foreach (JsonData tournamentConfig in tournamentConfigs)
{
    var playerInfo = new BC_PlayerInfo(tournamentConfig);
    playerInfoList.Add(playerInfo);

    string _tournamentCode = playerInfo.TournamentCode;
    Debug.Log(_tournamentCode);
    TituloTorneo.text = _tournamentCode;

    string _description = playerInfo.Description;
    Debug.Log(_description);
    DescripcionTorneo.text = _description;
}

and probably also for the lblist.

Upvotes: 1

Aiden Faulconer
Aiden Faulconer

Reputation: 422

I recommend using Unity's built-in solution to JSON, JsonUtility.FromJson() and it will autofill the following class scheme(from http://json2csharp.com/#), which should be easier to handle and not require an external library. Of course, this is an alternative, perhaps you may prefer to keep using LitJson, this should read "desc": "en". to implement this you would use...

    public class JsonHelper : MonoBehaviour
    {
      public RootObject jsonToRootObject; //access this with your for/foreach loops
      void start(){
      jsonToRootObject = JsonUtility.FromJson<RootObject>(place your json string here);
      }
    }



[Serializable]
public class Data2
{
    public string nickname;
}
[Serializable]
public class LeaderboardEnrollment
{
    public int score;
    public Data2 data;
    public long createdAt;
    public long updatedAt;
    public string tCode;
    public int tRank;
    public int tClaimedAt;
    public int tNotifiedAt;
}
[Serializable]
public class TournamentTimetable
{
    public long tRegistrationStart;
    public string tState;
    public long tPlayEnd;
    public long tRegistrationEnd;
    public long tPlayStart;
}
[Serializable]
public class Name
{
    public string en;
}
[Serializable]
public class Desc
{
    public string en;
}
[Serializable]
public class Description
{
    public Name name;
    public Desc desc;
}
[Serializable]
public class CustomJson
{
}
[Serializable]
public class EntryFee
{
}
[Serializable]
public class TournamentConfig
{
    public string tournamentCode;
    public Description description;
    public CustomJson customJson;
    public List<object> payoutRules;
    public EntryFee entryFee;
}
[Serializable]
public class Data
{
    public long server_time;
    public LeaderboardEnrollment leaderboardEnrollment;
    public int versionId;
    public TournamentTimetable tournamentTimetable;
    public List<TournamentConfig> tournamentConfigs;
    public bool enrolled;
}
[Serializable]
public class RootObject
{
    public Data data;
    public int status;
}

Upvotes: 1

Related Questions