我正在尝试使用 JSon.Net 库解析一些 JSON。该文档似乎有点稀疏,我对如何完成我需要的内容感到困惑。这是我需要解析的 JSON 格式。
{
"displayFieldName" : "OBJECT_NAME",
"fieldAliases" : {
"OBJECT_NAME" : "OBJECT_NAME",
"OBJECT_TYPE" : "OBJECT_TYPE"
},
"positionType" : "point",
"reference" : {
"id" : 1111
},
"objects" : [ {
"attributes" : {
"OBJECT_NAME" : "test name",
"OBJECT_TYPE" : "test type"
},
"position" : {
"x" : 5,
"y" : 7
}
} ]
}
我真正需要的唯一数据是对象数组中的内容。我是否可以使用 JsonTextReader 之类的东西来解析它,然后取出我想要的东西,例如 OBJECT_TYPE 以及 x 和 y 位置?我似乎无法得到JSonTextReader
按照我想要的方式工作,但我几乎找不到它的使用示例。
似乎首先序列化然后对我的对象使用 LINQ 将是理想的选择,我找到的每个示例都讨论首先序列化 JSON,但我不确定如何为此结构构建对象。特别是对象数组,它需要类似于属性和位置对象对的列表。我不知道如何编码我的对象,以便 JSon.Net 知道如何序列化它。
我以为我可以编写自己的简单解析器,将我需要的所有内容提取到我创建的属性对象中,但我运气不佳。
希望这一切都有意义,有什么想法吗?
我不知道 JSON.NET,但它可以很好地工作JavaScriptSerializer
from System.Web.Extensions.dll
(.NET 3.5 SP1):
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
public string OBJECT_NAME { get; set; }
public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
public int id { get; set; }
}
public class SubObject
{
public NameTypePair attributes { get; set; }
public Position position { get; set; }
}
public class Position
{
public int x { get; set; }
public int y { get; set; }
}
public class Foo
{
public Foo() { objects = new List<SubObject>(); }
public string displayFieldName { get; set; }
public NameTypePair fieldAliases { get; set; }
public PositionType positionType { get; set; }
public Ref reference { get; set; }
public List<SubObject> objects { get; set; }
}
static class Program
{
const string json = @"{
""displayFieldName"" : ""OBJECT_NAME"",
""fieldAliases"" : {
""OBJECT_NAME"" : ""OBJECT_NAME"",
""OBJECT_TYPE"" : ""OBJECT_TYPE""
},
""positionType"" : ""point"",
""reference"" : {
""id"" : 1111
},
""objects"" : [
{
""attributes"" : {
""OBJECT_NAME"" : ""test name"",
""OBJECT_TYPE"" : ""test type""
},
""position"" :
{
""x"" : 5,
""y"" : 7
}
}
]
}";
static void Main()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
Foo foo = ser.Deserialize<Foo>(json);
}
}
Edit:
Json.NET 使用相同的 JSON 和类来工作。
Foo foo = JsonConvert.DeserializeObject<Foo>(json);
Link: 使用 Json.NET 序列化和反序列化 JSON http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)