我真的对json感到困惑(我还在学习json )。
我想要的JSON:
{ "entityMap": {
"0": {
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
},
"1": {
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
},
"2": {
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
},
"3": {
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
}
}
}这被认为是糟糕的json吗?以及如何使用这样的数字命名json?
到目前为止,我得到的就是这些。
{
"entityMap": [
{
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
},
{
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
},
{
"type": "LINK",
"mutability": "MUTABLE",
"data": {
"url": "https://stackoverflow.com/"
}
}
]
}这是我的课
public class editorRawTest
{
public List<entityMapItem> entityMap { get; set; }
}
public class entityMapItem
{
public string type { get; set; }
public string mutability { get; set; }
public entityMapItemData data { get; set; }
}
public class entityMapItemData
{
public string url { get; set; }
}我的执行代码:
var map = new List<entityMapItem>();
var mapitem = new entityMapItem() { type = "LINK", mutability = "MUTABLE", data = new entityMapItemData() { url = "https://stackoverflow.com/" } };
map.Add(mapitem);
map.Add(mapitem);
map.Add(mapitem);
editorRawTest bc = new editorRawTest() { entityMap = map };
string JSONresult = JsonConvert.SerializeObject(bc);
string path = @"jsonmapdata.json";
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(JSONresult.ToString());
tw.Close();
}搜索谷歌和堆栈溢出没有运气。任何线索或帮助都将不胜感激。
谢谢。
发布于 2020-04-14 06:12:32
要获得第一个JSON,您需要将List<entityMapItem>替换为Dictionary<string, entityMapItem>,如下所示:
public class editorRawTest
{
public Dictionary<string, entityMapItem> entityMap { get; set; }
}然后您需要像这样填充它:
var map = new Dictionary<string, entityMapItem>();
var mapitem = new entityMapItem() { type = "LINK", mutability = "MUTABLE", data = new entityMapItemData() { url = "https://stackoverflow.com/" } };
for (int i = 0; i < 4; i++)
{
map.Add(i.ToString(), mapitem);
}但除非迫不得已,否则我不会鼓励你这么做。您现在所拥有的(列表中的第二个JSON )更容易使用。如果您可以在这两种方法中进行选择,最好选择第二种方法。有关原因,请参阅Using json key to store value, is it a good approach?。
https://stackoverflow.com/questions/61197274
复制相似问题