我必须来自数据库API的JSON响应。
我的JSON数据:
{
"AccessToken":"1929c63a-9c72-4c0d-aea8-345c0b5411e9",
"LoggedInUserID":1,
"LookupData":{
"LiquiditySources":[
{
"ID":1,
"ParentID":null,
"Name":"testname1",
"SequenceNo":null,
"Caption":"test1",
"ConnectivityInfo":
"{\"Port\":11111,\"Username\":testuser1,\"Password\":\"password1\"}"
},
{
"ID":2,
"ParentID":null,
"Name":"testname2",
"SequenceNo":null,
"Caption":"test2",
"ConnectivityInfo":
"{\"Port\":22222,\"Username\":testuser2,\"Password\":\"password2\"}"
}
]
}
}
我想将这个响应值存储在不同的变量中,请任何人帮助我这是我的最后一年项目。我正在使用Windows应用程序c#
答案 0 :(得分:1)
您应该将此JSON反序列化为类,然后使用类对象执行任何操作。
您可以使用NewtonSoft.Json dll来实现此目的。
public class LiquiditySource
{
public int ID { get; set; }
public object ParentID { get; set; }
public string Name { get; set; }
public object SequenceNo { get; set; }
public string Caption { get; set; }
public string ConnectivityInfo { get; set; }
}
public class LookupData
{
public List<LiquiditySource> LiquiditySources { get; set; }
}
public class SampleClass
{
public string AccessToken { get; set; }
public int LoggedInUserID { get; set; }
public LookupData LookupData { get; set; }
}
string json = "your json string";
SampleClass obj = JsonConvert.DeserializeObject<SampleClass>(json);
您可以获得以下属性:
List<LiquiditySource> ls = obj.LookupData.LiquiditySources;
foreach(LiquiditySource liquiditySource in ls)
{
string connectivityInfo = liquiditySource.ConnectivityInfo;
}
如果您只想获取所有ConnectivityInfo
值,也可以使用LINQ
。
List<string> lsConnectivityInfo = obj.LookupData.LiquiditySources.Select(c => c.ConnectivityInfo).ToList();
如果你想将connectivityInfo
字符串deserilize到object并获取它的属性,那么你必须再次将它反序列化为object。
注意:您还必须修改JSON。
修改JSON:
{
"AccessToken": "1929c63a-9c72-4c0d-aea8-345c0b5411e9",
"LoggedInUserID": 1,
"LookupData": {
"LiquiditySources": [{
"ID": 1,
"ParentID": null,
"Name": "testname1",
"SequenceNo": null,
"Caption": "test1",
"ConnectivityInfo": "{\"Port\":11111,\"Username\":\"testuser1\",\"Password\":\"password1\"}"
}, {
"ID": 2,
"ParentID": null,
"Name": "testname2",
"SequenceNo": null,
"Caption": "test2",
"ConnectivityInfo": "{\"Port\":22222,\"Username\":\"testuser2\",\"Password\":\"password2\"}"
}]
}
}
再上一堂课:
public class ConnectivityInfo
{
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
然后这样做:
foreach (LiquiditySource liquiditySource in ls)
{
string connectivityInfo = liquiditySource.ConnectivityInfo;
ConnectivityInfo connectivityInfoObj = JsonConvert.DeserializeObject<ConnectivityInfo>(connectivityInfo);
}