weaverbeaver
weaverbeaver

Reputation: 161

Deserializing JSON array into C# object

I really need some help with desereliazing a JSON.

Here is my JSON : https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD

Here is the code I have so far :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;

public class StockManager : MonoBehaviour {

private string webString;

private CurrencyContainer container;

[SerializeField]private int currenciesToLoad;

void Start()
{
    StartCoroutine(GetText());
}

void Update()
{
    if (container != null) 
    {
        Debug.Log (container.Arr);
    } 
    else 
    {
        Debug.Log ("null");
    }
}

IEnumerator GetText()
{
    using (WWW www = new WWW("https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD"))
    {
        yield return www;

        if (www.error != null)
        {
            Debug.Log("Error is : " + www.error);
        }
        else
        {
            webString = "{ \"Arr\":" + www.text + "}";

                            container = JsonConvert.DeserializeObject<CurrencyContainer> (webString);

        }
    }       
}

[System.Serializable]
public class Datum
{
    public int time;
    public double close;
    public double high;
    public double low;
    public double open;
    public double volumefrom;
    public double volumeto;
}

[System.Serializable]
public class ConversionType
{
    public string type;
    public string conversionSymbol;
}

[System.Serializable]
public class Example
{
    public string Response;
    public int Type;
    public bool Aggregated;
    public IList<Datum> Data;
    public int TimeTo;
    public int TimeFrom;
    public bool FirstValueInArray;
    public ConversionType ConversionType;
}

[System.Serializable]
public class CurrencyContainer
{
    public Example[] Arr;
}

}

The error I get is : JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'StockManager+Example[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

I have no idea how to fix and any help is really appreciated. Thanks a lot.

Upvotes: 0

Views: 642

Answers (1)

Christoph Fink
Christoph Fink

Reputation: 23113

You have "one level to much" in your object structure, as the given JSON is only on "item" of your type Example. Try the following:

var item = JsonConvert.DeserializeObject<Example>(www.text);

See it HERE in action.

Upvotes: 1

Related Questions