gpt4 book ai didi

c# - 从字符串中提取键值对

转载 作者:太空宇宙 更新时间:2023-11-03 21:16:18 26 4
gpt4 key购买 nike

我有以下字符串:

string myString = "{'gridObject':'[1,2,3,4],[5,6,7,8]'}";

我如何将它处理成一个对象,以便我可以这样做:

charts[0]     //=> [1,2,3,4]
charts[0][1] //=> 2

如果我能把它转换成这个对象,那就更好了:

public class gridObject {

public int datarow {get; set;}
public int datacol {get; set;}
public int datasizex {get; set;}
public int datasizey {get; set;}

}

最佳答案

这就是我会做的。

首先创建你的类,

public class GridObject
{
public int datarow { get; set; }
public int datacol { get; set; }
public int datasizex { get; set; }
public int datasizey { get; set; }
}

public class GridObjectCollection
{
public GridObject[] GridObjects { get; set; }
}

然后,看看你需要什么 JSON,序列化一次:(JsonConvert 是 Json.NET 的一部分,你可以用 NuGet 得到它)

GridObjectCollection gridObjects = new GridObjectCollection();
gridObjects.GridObjects = new GridObject[]
{
new GridObject() { datacol = 1, datarow = 2, datasizex = 3, datasizey = 4 },
new GridObject() { datacol = 5, datarow = 6, datasizex = 7, datasizey = 8 }
};

Console.WriteLine
(
JsonConvert.SerializeObject
(
gridObjects,
new JsonSerializerSettings() { Formatting = Formatting.Indented }
)
);

在这里您可以看到反序列化时将生成这些类的有效 JSON 内容如下:

{
"GridObjects": [
{
"datarow": 2,
"datacol": 1,
"datasizex": 3,
"datasizey": 4
},
{
"datarow": 6,
"datacol": 5,
"datasizex": 7,
"datasizey": 8
}
]
}

然后,尝试反序列化以确保:

var f = JsonConvert.DeserializeObject<GridObjectCollection>
(
"{'GridObjects':[{'datarow':2,'datacol':1,'datasizex':3,'datasizey':4},{'datarow':6,'datacol':5,'datasizex':7,'datasizey':8}]}"
);

关于c# - 从字符串中提取键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34054442/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com