Home > Enterprise >  How to parse JSON string to C# Object in Unity
How to parse JSON string to C# Object in Unity

Time:10-21

So I have this JSON, retrieved from UnityWebRequest response:

    {
       "data":{
          "attributes":{
             "email":"[email protected]",
             "first_name":"XXX",
             "full_name":"XXX",
             "image_url":"https://c8.patreon.com/2/200/XXX",
             "is_email_verified":true,
             "last_name":"",
             "thumb_url":"https://c8.patreon.com/2/200/XXX",
             "url":"https://www.patreon.com/user?u=XXX",
             "vanity":null
          },
          "id":"XXX",
          "relationships":{
             "memberships":{
                "data":[
                   {
                      "id":"XXX",
                      "type":"member"
                   }
                ]
             }
          },
          "type":"user"
       },
       "included":[
          {
            

 "attributes":{
            "currently_entitled_amount_cents":100,
            "last_charge_date":"2021-10-20T10:09:42.000 00:00",
            "last_charge_status":"Paid",
            "lifetime_support_cents":116,
            "patron_status":"active_patron",
            "pledge_relationship_start":"2021-10-20T10:09:40.763 00:00"
         },
         "id":"XXX",
         "type":"member"
      }
   ],
   "links":{
      "self":"https://www.patreon.com/api/oauth2/v2/user/XXX"
   }
}

I have problems parsing it in such a way that I can easily access the attributes as a variable. In particular, I need to get the value of currently_entitled_amount_cents. I have actually no clue how it works, so please help me. I couldn't find any good example of doing this on the internet.

EDIT: I tried it with JsonUtility.FromJson, but it will not work.

using System.Collections;
using UnityEngine.Networking;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript2 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // A correct website page.
        StartCoroutine(GetRequest("https://www.example.com"));

    // A non-existing page.
    StartCoroutine(GetRequest("https://error.html"));
}

// Update is called once per frame
void Update()
{

}

IEnumerator GetRequest(string uri)
{
    using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
    {
        // Request and wait for the desired page.
        yield return webRequest.SendWebRequest();

        string[] pages = uri.Split('/');
        int page = pages.Length - 1;

        switch (webRequest.result)
        {
            case UnityWebRequest.Result.ConnectionError:
            case UnityWebRequest.Result.DataProcessingError:
                Debug.LogError(pages[page]   ": Error: "   webRequest.error);
                break;
            case UnityWebRequest.Result.ProtocolError:
                Debug.LogError(pages[page]   ": HTTP Error: "   webRequest.error);
                break;
            case UnityWebRequest.Result.Success:
                Debug.Log(pages[page]   ":\nReceived: "   webRequest.downloadHandler.text);
                JsonClass JsonClass = JsonUtility.FromJson<JsonClass>(webRequest.downloadHandler.text);
                Debug.Log(JsonClass.included.attributes.currently_entitled_amount_cents);
                break;
        }
    }
}
}

[System.Serializable]
public class JsonClass
{
    public Included[] included;
}

[System.Serializable]
public class Included
{
    public Attributes attributes;
}

[System.Serializable]
public class Attributes
{
    public int currently_entitled_amount_cents;
}

Console error

error CS1061: 'Included[]' does not contain a definition for 'attributes' and no accessible extension method 'attributes' accepting a first argument of type 'Included[]' could be found (are you missing a using directive or an assembly reference?)

CodePudding user response:

included is an array of multiple Include elements so you probably want

JsonClass.included[0].attributes.currently_entitled_amount_cents

in order to simply take the first element. If there are more items later it is up to you how to figure out which of these elements you want to access.


in general you should avoid to name a variable the same as its type so instead of

JsonClass JsonClass

I would rather use

JsonClass jsonClass

CodePudding user response:

the easiest way will be using System.Text.Json parser, but I recommend to install Newtonsoft.Json parser

var json= webRequest.downloadHandler.text;
var objects = JObject.Parse(json); 
var amountCents=objects["included"][0]["attributes"]["currently_entitled_amount_cents"];

output

100

the more complicated way is to deserialize json, but in this case you will have much easy acces to any properties and you can even use Linq for a search

var jsonDeserealized = JsonConvert.DeserializeObject<Data>(json);
var currentlyEntitledAmountCents=jsonDeserealized.Included[0].Attributes.CurrentlyEntitledAmountCents;

classes

public partial class Data
    {
        [JsonProperty("data")]
        public DataClass DataData { get; set; }

        [JsonProperty("included")]
        public Included[] Included { get; set; }

        [JsonProperty("links")]
        public Links Links { get; set; }
    }

    public partial class DataClass
    {
        [JsonProperty("attributes")]
        public DataAttributes Attributes { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("relationships")]
        public Relationships Relationships { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }
    }

    public partial class DataAttributes
    {
        [JsonProperty("email")]
        public string Email { get; set; }

        [JsonProperty("first_name")]
        public string FirstName { get; set; }

        [JsonProperty("full_name")]
        public string FullName { get; set; }

        [JsonProperty("image_url")]
        public Uri ImageUrl { get; set; }

        [JsonProperty("is_email_verified")]
        public bool IsEmailVerified { get; set; }

        [JsonProperty("last_name")]
        public string LastName { get; set; }

        [JsonProperty("thumb_url")]
        public Uri ThumbUrl { get; set; }

        [JsonProperty("url")]
        public Uri Url { get; set; }

        [JsonProperty("vanity")]
        public object Vanity { get; set; }
    }

    public partial class Relationships
    {
        [JsonProperty("memberships")]
        public Memberships Memberships { get; set; }
    }

    public partial class Memberships
    {
        [JsonProperty("data")]
        public Datum[] Data { get; set; }
    }

    public partial class Datum
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }
    }

    public partial class Included
    {
        [JsonProperty("attributes")]
        public IncludedAttributes Attributes { get; set; }

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }
    }

    public partial class IncludedAttributes
    {
        [JsonProperty("currently_entitled_amount_cents")]
        public long CurrentlyEntitledAmountCents { get; set; }

        [JsonProperty("last_charge_date")]
        public DateTimeOffset LastChargeDate { get; set; }

        [JsonProperty("last_charge_status")]
        public string LastChargeStatus { get; set; }

        [JsonProperty("lifetime_support_cents")]
        public long LifetimeSupportCents { get; set; }

        [JsonProperty("patron_status")]
        public string PatronStatus { get; set; }

        [JsonProperty("pledge_relationship_start")]
        public DateTimeOffset PledgeRelationshipStart { get; set; }
    }

    public partial class Links
    {
        [JsonProperty("self")]
        public Uri Self { get; set; }
    }
  • Related