我正在尝试使用 C# 中的数据协定来解析 JSON 文件,但是我遇到了一个问题,因为成员名称并不总是恒定的,但结构却是恒定的。
以这个 JSON 为例(由纹理打包器创建):
{
"frames": {
"frame-abc":
{
"frame": {"x":41,"y":2,"w":256,"h":256},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":256,"h":256},
"sourceSize": {"w":256,"h":256}
},
"someframe":
{
"frame": {"x":2,"y":2,"w":37,"h":382},
"rotated": false,
"trimmed": false,
"spriteSourceSize": {"x":0,"y":0,"w":37,"h":382},
"sourceSize": {"w":37,"h":382}
}
}
}
我将如何为其创建 DataContract? 请注意,“frame-abc”和“someframe”具有完全相同的结构,但名称不同。 所以我想要一个具有框架数组的类(每个框架都有框架、旋转、修剪、spriteSourceSize 和 sourceSize 元素),将从这个 JSON 文件加载。
最佳答案
不,您无法为其创建DataContract
。但在Json.net的帮助下和 Linq,你可以这样做:
var jObj = JObject.Parse(json);
var frameDict = jObj["frames"].Children()
.OfType<JProperty>()
.ToDictionary(p => p.Name, p => p.Value.ToObject<Frame>());
public class Rect
{
public int x { get; set; }
public int y { get; set; }
public int w { get; set; }
public int h { get; set; }
}
public class SSize
{
public int w { get; set; }
public int h { get; set; }
}
public class Frame
{
public Rect frame { get; set; }
public bool rotated { get; set; }
public bool trimmed { get; set; }
public Rect spriteSourceSize { get; set; }
public SSize sourceSize { get; set; }
}
关于具有非常量变量名称的 C# DataContract,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16865927/