Skip to main content
 首页 » 编程设计

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

2024年02月05日23jirigala

我有以下字符串:

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}]}" 
);