【问题标题】:How to deserialize a List<float> from a JSON string?如何从 JSON 字符串反序列化 List<float>?
【发布时间】:2019-12-07 16:49:59
【问题描述】:

这是我的 JSON 字符串,它只代表一个简单的列表: {"accelerationsList":"[-3.1769, 3.304, 6.3455997, 3.1701]"}

这是我的反序列化 C# 代码:

HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result; // i know about deadlock...
List<float> accelerationsList = new JavaScriptSerializer().Deserialize<List<float>>(jsonContent);

我不知道为什么我的AccelerationsList 是空的!有什么建议吗?

【问题讨论】:

  • 可能是因为它是 JSON 中的字符串,而不是浮点数列表。此外,您需要一个表示 JSON 对象的类型。看看here
  • 那真的是你的 JSON 吗?数组实际上是一个字符串吗?还是真的是一个数组?
  • 是的,这是我的 JSON 和加速列表,它来自我的 Java 代码:List&lt;Float&gt; accelerationsList = new ArrayList&lt;&gt;();
  • 你的json不是float数组,它是一个对象,有一个名为accelerationsList的属性,它有一个字符串值,它的内容看起来像一个float的json数组。

标签: c# json


【解决方案1】:

使用 Newtonsoft.Json,它会变得干净

string accelerationsListString = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonContent)["accelerationsList"];
List<float> accelerationsList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<float>>(accelerationsListString);

你得到一个字符串中float的列表,所以我们需要将字符串提取后转换为列表

【讨论】:

  • Newtonsoft.Json.JsonSerializationException: '将值“[-3.6553, -3.1338, -3.1062]”转换为类型“System.Collections.Generic.List1[System.Single]'. Path 'accelerationsList', line 1, position 50.' Inner Exception ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.List1[System.Single] 时出错。
  • 你得到一个字符串中float的列表,所以我们需要将字符串提取后转换为列表。这会工作
  • 我想你明白了,谢谢!现在我需要做同样的事情,但对于 List 所以也许你很快就会看到啊
【解决方案2】:

我相信除了 1 个问题之外,您拥有大部分您想要的东西。

您正在尝试将整个内容(json 字符串)转换为 List。您需要正确转换json对象以获得accelerationsList的值,然后正确转换作为您的Floats列表的字符串。

string jsonContent = @"{""accelerationsList"":""[-3.1769, 3.304, 6.3455997, 3.1701]""}";
var stringRepOfArray = JObject.Parse(jsonContent)["accelerationsList"].ToString();

List<float> floatList = new JavaScriptSerializer().Deserialize<List<float>>(stringRepOfArray);

输出:

floatList
Count = 4
    [0]: -3.1769
    [1]: 3.304
    [2]: 6.34559965
    [3]: 3.1701

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2021-09-02
    相关资源
    最近更新 更多