【问题标题】:Deserializing JSON array into C# object将 JSON 数组反序列化为 C# 对象
【发布时间】:2018-01-31 09:29:34
【问题描述】:

我真的需要一些帮助来解散 JSON。

这是我的 JSON:https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD

这是我到目前为止的代码:

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;
}

}

我得到的错误是:JsonSerializationException: 无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“StockManager+Example[]”,因为该类型需要 JSON 数组(例如 [1, 2,3]) 正确反序列化。

我不知道如何解决,非常感谢任何帮助。 非常感谢。

【问题讨论】:

  • 你能发布你的 Json 字符串吗?

标签: c# json serialization json.net deserialization


【解决方案1】:

您的对象结构中有“一个级别”,因为给定的 JSON 仅在您的类型 Example 的“项目”上。请尝试以下操作:

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

查看HERE 的实际应用。

【讨论】:

  • 就可以了。这一行 webString = "{ \"Arr\":" + www.text + "}";也没有做任何好事。
  • 另外,我将如何打印 Data 中的每个值?例如,如果我打印 data(0) 我应该得到 {"time":1514764800,"close":13444.88,"high":13921.53,"low":12877.67,"open":13850.49,"volumefrom":78425.21," volumeto":1057521524.42} ,data(1) 应该打印:"time":1514851200,"close":14754.13,"high":15306.13,"low":12934.16,"open":13444.88,"volumefrom":137732.17,"卷“:1956783037.35。好吧,我知道它不会那样工作,因为 Data 是一个只有一个元素的数组,但是我怎样才能实现我想要的呢?再次非常感谢。
  • @weaverbeaver 您可以通过item.Data[index] 访问它们,例如item.Data[0]。 (我将小提琴更新为转储数据(0)和数据(1))
  • 是的,我使用的是 item.Data(index) 而不是 item.Data[index]。再次非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多