Get Specific Data From Json Response

Morning,

I am working with getting data from a webserver for the first time. I am using Rest Client to Json and I am getting a response but the way the client structured the API call the content I need is buried deep in the resonse. I am still learning and I have tried for a week before this post. Here is what I get back:

[RestApi] Success {“success”:true,
“user_id”:“2”,
“room”:“1”,
“username”:“user”,
“error”:“”,“errorCode”:0,
“page”:“Life Sciences and Healthcare”,
“resources”:{“text”:{“1”:{“id”:“1”,
title”:“Cloud Computing”,
body”:“Healthcare enterprises must ensure the safety of protected health information (PHI) on the patient side and for those that double as insurance carriers, the secure storage and transmission of claims information must also be considered.”}},
button”:{“2”:{“id”:“2”,“button”:“TheFacebook”,“action”:“https://www.facebook.com”}},
media”:{“2”:{“id”:“2”,“filename”:“testing.png”,“poster”:“poster.jpg”,“mediatype”:“i”}}}}

I am simply trying to get “title” and “body”.

I guess my issue is that I do not understand how to sort through the post response and get data out.

Very helpful

You can simply define a class with only the fields you care about and use JsonUtility to deserialize the json into that class. the utility will skip fields that are not defined in the class (and fields that are omitted in the JSON) when writing/overwriting the fields in the class.

[System.Serializable]
public class Article
{
    public string title;
    public string body;
}

public Article LoadArticle(string jsonString)
{
    return JsonUtility.FromJson<Article >(jsonString);
}
3 Likes

You can’t use that class exactly because it doesn’t match the structure of the JSON in the OP (which isn’t obvious, because the posted JSON is misleadingly formatted, but “title” and “body” are not top-level members).

But in general terms, you define a class that matches the structure of the data you want to pass, you feed that class plus the JSON into some JSON deserializer. Whichever JSON deserializer you are using probably has examples of the proper syntax for this.

If you are not using a JSON deserializer, then pick one to use. Unity has a limited but serviceable one built-in, there’s some more robust ones you can download for free.

2 Likes

Thank you guys. I am using RestClient. I was told to try Newtonsoft because the client wants to be able to have numerous bodies, titles and buttons and supposedly Newtonsoft has the ability to work without defining a class with the exact paramaters? I have been searching for information to support this before I switch.

Ok I have made some progress. Now I just need to figure out how to get the nested data out. Any help would be appreciated.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft;
using UnityEngine.Networking;
using System.Text;
using System;
using Newtonsoft.Json;
using UnityEngine.UI;
using System.Linq;

[Serializable]
public class APIPostResult
{
    public string request;
    public string key;
    public string user;
    public string page;
}

public class PageResources
{
    public string title;
    public string body;
}


public class APIPostRequest : MonoBehaviour
{
    private string URL = Hidden;
    private string APIKEY = Hidden
    private string FetchType = "fetchPageResources";
    public string User = "2";
    public string Page = "1";

    public void Start()
    {
        StartCoroutine(PostRequest(URL));
    }

    IEnumerator PostRequest(string url)
    {
        var json = new Dictionary<string, object>();
        json.Add("request", FetchType);
        json.Add("key", APIKEY);
        json.Add("user", User);
        json.Add("page", Page);

        var req = new APIPostResult();

        var jconverted = JsonConvert.SerializeObject(json);
        byte[] jsonSent = new System.Text.UTF8Encoding().GetBytes(jconverted);

        var request = new UnityWebRequest(url, "Post");

        request.SetRequestHeader("Content-Type", "application/json");
        request.uploadHandler = new UploadHandlerRaw(jsonSent);
        request.downloadHandler = new DownloadHandlerBuffer();

        yield return request.SendWebRequest();

        if (request.error != null)
        {
            Debug.Log("Error While Sending: " + request.error);
        }
        else
        {
            Debug.Log("All OK");
            Debug.Log("Received: " + request.downloadHandler.text);

            PageResources res = JsonConvert.DeserializeObject<PageResources>(request.downloadHandler.text);

            Debug.Log(res.title);
        }
    }

}