简体   繁体   中英

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 (eg {"name":"value"}) into type 'StockManager+Example[]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM