如何解决无法从JSON格式检索正确的值需要协助
在从C#中的JSON对象获取值方面,我需要一点帮助。这是代码和输出。我正在尝试从两个对象中检索ScoreRepresentation
的值。根据以下输出,在这种情况下,获得的值为BR400L
和null
。
有人可以帮助吗? C#中的新手:)预先感谢
using System;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var json = "{\"Results\":[{\"RequestIdentifier\":\"Lexile\",\"ValueType\":\"INTEGER\",\"Scores\":[{\"lexile\":{\"ScoreValue\":-400,\"ScaledScore\":-400,\"ScoreRepresentation\":\"BR400L\"}}]},{\"RequestIdentifier\":\"UnifiedScaleScore\",\"Scores\":[{\"unifiedScaleScore\":{\"ScoreValue\":610,\"ScaledScore\":610,\"ScoreRepresentation\":null}}]}]}";
var deserialized = JsonConvert.DeserializeObject(json);
Console.WriteLine(deserialized);
}
}
}
输出:
{
"Results": [
{
"RequestIdentifier": "Lexile","ValueType": "INTEGER","Scores": [
{
"lexile": {
"ScoreValue": -400,"ScaledScore": -400,"ScoreRepresentation": "BR400L"
}
}
]
},{
"RequestIdentifier": "UnifiedScaleScore","Scores": [
{
"unifiedScaleScore": {
"ScoreValue": 610,"ScaledScore": 610,"ScoreRepresentation": null
}
}
]
}
]
}
解决方法
我喜欢走“模型”路线。您创建数据模型,然后可以轻松地反序列化它们。有时候,当我感到懒惰时,我会使用this site为我完成工作。
因此,对于您的特定示例,它返回了以下模型:
public class Lexile {
public int ScoreValue { get; set; }
public int ScaledScore { get; set; }
public string ScoreRepresentation { get; set; }
}
public class UnifiedScaleScore {
public int ScoreValue { get; set; }
public int ScaledScore { get; set; }
public object ScoreRepresentation { get; set; }
}
public class Score {
public Lexile lexile { get; set; }
public UnifiedScaleScore unifiedScaleScore { get; set; }
}
public class Result {
public string RequestIdentifier { get; set; }
public string ValueType { get; set; }
public List<Score> Scores { get; set; }
}
public class Root {
public List<Result> Results { get; set; }
}
然后,您只需执行以下操作即可反序列化为Root
:
var deserialized = JsonConvert.DeserializeObject<Root>(json);
请记住,如果您的JSON不完美,您将发现与输出存在一些不一致之处。您可能需要对模型进行一些调整以解决这些问题。您不能仅仅假设该站点为您提供100%准确的数据。
但是,如果足够好,您现在可以获取所需的每个属性,而无需动用动态特性或JToken
。
例如:
foreach(var r in deserialized.Results)
{
foreach(var s in r.Scores)
{
Console.Write(s.unifiedScaleScore.ScoreRepresentation);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。