将JSON数组反序列化为C#对象 [英] Deserializing JSON array into C# object

查看:315
本文介绍了将JSON数组反序列化为C#对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的需要一些反序列化JSON的帮助.

I really need some help with desereliazing a JSON.

这是我的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;
}

}

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

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.

推荐答案

由于给定的JSON仅位于类型为Example的"item"上,因此对象结构中的级别达到一级".请尝试以下操作:

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

此处查看.

这篇关于将JSON数组反序列化为C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆