简体   繁体   English

将JSON数组反序列化为C#对象

[英]Deserializing JSON array into C# object

I really need some help with desereliazing a JSON. 我确实需要一些反序列化JSON的帮助。

Here is my JSON : https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD 这是我的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. 我得到的错误是:JsonSerializationException:无法将当前JSON对象(例如{“ name”:“ value”})反序列化为类型'StockManager + Example []',因为该类型需要JSON数组(例如[1,2,3 ])正确反序列化。

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 . 您的对象结构中有“一个级别到一个级别”,因为给定的JSON仅位于类型Example “ item”上。 Try the following: 请尝试以下操作:

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

See it HERE in action. 这里看到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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