esperantooo
esperantooo

Reputation: 1

Getting Json data from API and Displaying only part of the json in Unity C#

I'm having trouble getting just the price value from this API. I don't need all the JSON that's coming from the web URL, I only need the "rate":"3,394.2033" part.

API Data:

{
  "time": {
    "updated": "Feb 6, 2019 22:02:00 UTC",
    "updatedISO": "2019-02-06T16:02:00-06:00",
    "updateduk": "Feb 6, 2019 at 22:02 GMT"
  },
  "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
  "bpi": {
    "USD": {
      "code": "USD",
      "rate": "3,394.2033",
      "description": "United States Dollar",
      "rate_float": 3394.2033
    },
    "XBT": {
      "code": "XBT",
      "rate": "1.0000",
      "description": "Bitcoin",
      "rate_float": 1
    }
  }
}

My Code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class API : MonoBehaviour
{
    private string www = 
    "https://api.coindesk.com/v1/bpi/currentprice/XBT.json";
    public Text responseText;

    public void Request()
    {
        WWW request = new WWW(www);
        StartCoroutine(OnResponse(request));
    }
    private IEnumerator OnResponse(WWW req)
    {
        yield return req;

        responseText.text = req.text;
    }
}

This script allows me to pull all the JSON data but I only need the "rate":"3,394.2033". More specifically, just the value 3,394.2033.

Upvotes: 0

Views: 2304

Answers (4)

Carlos R
Carlos R

Reputation: 1

You can use UnityWebRequest.Get to get the JSON and then use a library to deserialize it (I'd recommend NewtonSoft.Json).

After deserializing the JSON you can choose which properties to use from the resulting object.

I put together a tutorial doing just that and a bit more.

https://www.youtube.com/watch?v=Yp8uPxEn6Vg

Upvotes: 0

derHugo
derHugo

Reputation: 90852

You can also use the old but gold SimpleJSON from the Unity community

To use SimpleJSON in Unity you just have to copy the SimpleJSON.cs file into your projects "plugins" folder inside your assets folder.

and do e.g.

var json = JSON.Parse(req.text);
var yourText = json["bpi"]["USD"]["rate"];

Note for debugging

If the given key wasn't found in contrary to what you would expect this returns null instead of throwing an exception.

Upvotes: 0

Brian Rogers
Brian Rogers

Reputation: 129827

Using Json.Net's LINQ-to-JSON API (JTokens) you can do this with one line of code:

var rate = (string)JToken.Parse(json).SelectToken("bpi.USD.rate");

Fiddle: https://dotnetfiddle.net/Krgejr

Upvotes: 1

Shim-Sao
Shim-Sao

Reputation: 2126

You can use newtonsoft and follow this example here : https://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm

public class SearchResult
{
    public string Rate { get; set; }
}


JObject rateSearch = JObject.Parse(MyJsonText);

// get JSON result objects into a list
IList<JToken> results = rateSearch ["bpi"]["USD"].Children().ToList();

// serialize JSON results into .NET objects
IList<SearchResult> searchResults = new List<SearchResult>();
foreach (JToken result in results)
{
    // JToken.ToObject is a helper method that uses JsonSerializer internally
    SearchResult searchResult = result.ToObject<SearchResult>();
    searchResults.Add(searchResult);
}

Upvotes: 0

Related Questions