【问题标题】:JSON to array in C#JSON到C#中的数组
【发布时间】:2018-09-13 01:27:05
【问题描述】:

我有一个生成 JSON 格式的程序。我想要做的是将 json 结果存储到 C# 中的数组中。

从 API 接收的 json:

var strResponseContent = await response.Content.ReadAsStringAsync();
Result.Text = strResponseContent.ToString(); **<-- this is working fine**

这是 json 的样子:

{
    "query": "banana",
    "topScoringIntent": {
        "intent": "banana",
        "score": 0.9086001
    },
    "intents": [{
            "intent": "banana",
            "score": 0.9086001
        }, {
            "intent": "bananania",
            "score": 0.559515059
        }
    ]
}

并将 json 存储到数组中。这是结构:

public class Intents
    {
        public List<Intent> intents { get; set; }
    }

    public class Intent
    {
        public string intent { get; set; }
        public int score { get; set; }
    }

最后,为了转换,我使用了反序列化对象

Intents intents = JsonConvert.DeserializeObject<Intent>(strResponseContent);

然而,在存储到 json 的过程中,错误就像 "can't implicitly convert type Intent to Intents"

我的错误是什么?如何纠正?

【问题讨论】:

  • 您将 Intent 作为类型参数传递给 DeserializeObject,您应该在其中传递 Intents

标签: c# arrays json


【解决方案1】:

有两件事首先 score 不是有效的 int...所以,尝试将 int 更改为 Decimal。 第二次尝试这样做:

Intents intents = JsonConvert.DeserializeObject<Intents>(strResponseContent);

【讨论】:

    【解决方案2】:

    您将分数定义为整数

     public int score { get; set; }
    

    但分数不是整数。将其更改为双精度或小数将修复它。

    【讨论】:

    • 我建议将您的答案与接受的答案进行比较,看看您哪里出错了 :-)
    • 约翰,我没有出错。当我回答这个问题时,杰拉尔多提到了第一个问题。我不想重复他的回答。我发现了另一个问题,我提到了它。我觉得这个答案后来通过添加分数问题进行了编辑。
    猜你喜欢
    • 2014-12-28
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多