我对编码很陌生,这是我的要求:
例如:最终结果应该像
string[] deleteValues = {"MCS:Menu:Admin","MCS:test"}
如果该问题已经有了答案,请指出正确的方向。
预先感谢
========================================
我能够通过这种方式获取值...
string value1 = new JavaScriptSerializer().Deserialize<JSON_Deconstructor>(resp).Permitted[0].Delete[0].ToString();
string value2 = new JavaScriptSerializer().Deserialize<JSON_Deconstructor>(resp).Permitted[0].Delete[1].ToString();
但是由于delete中值的数量是动态的,因此我需要了解如何拉动它们。
===================
代码段:
string resp = new StreamReader(request1.GetResponse().GetResponseStream()).ReadToEnd(); // resp is a JSON response from a server
JSON_Deconstructor dc = new JSON_Deconstructor { };
dc.Permitted = new Permitted[1];
string value1 = new JavaScriptSerializer().Deserialize<JSON_Deconstructor>(resp).Permitted[0].Delete[0].ToString();
string value2 = new JavaScriptSerializer().Deserialize<JSON_Deconstructor>(resp).Permitted[0].Delete[1].ToString();
=================
JSON_Deconstructor类内容:
public class JSON_Deconstructor
{
public Permitted[] Permitted { get; set; }
public Denied[] Denied { get; set; }
}
=================
允许的课程内容:
public class Permitted
{
public string[] Read { get; set; }
public string[] Update { get; set; }
public string[] Delete { get; set; }
}
=================
JSON响应:
{
"Permitted": [
{
"read": [
"MCS:Menu:Admin"
],
"update": [
"MCS:test"
],
"delete": [
"MCS:Menu:Admin",
"MCS:test"
]
}
]
}
答案 0 :(得分:1)
首先将jsonProperty添加到您的类中,以便能够进行序列化。
public class Permitted
{
[JsonProperty("read")]
public string[] Read { get; set; }
[JsonProperty("update")]
public string[] Update { get; set; }
[JsonProperty("delete")]
public string[] Delete { get; set; }
}
//Response contains a list of permitted objects in Permitted property
public class PermittedResponse
{
public List<Permitted> Permitted { get; set; }
}
然后在您的方法中取消序列化响应并遍历结果以构建阵列。
List<string> deletedValues = new List<string>();
List<string> readValues = new List<string>();
List<string> updateValues = new List<string>();
PermittedResponse response = JsonConvert.DeserializeObject<PermittedResponse>(serializedJson);
response.Permitted.ForEach(e =>
{
deletedValues = deletedValues.Concat(e.Delete).ToList();
readValues = readValues.Concat(e.Read).ToList();
updateValues = updateValues.Concat(e.Update ).ToList();
});
答案 1 :(得分:0)
使用Newtonsoft.Json。您可以从NuGet获取它。对于Json而言,这是一个非常简单且功能强大的库。
现在,您应该创建一个类,例如:
public class Item
{
public List<string> MCS { get; set; } = new List<string>();
}
public class PermitedItem
{
public Item read {get; set;}
public Item update {get; set;}
public Item delete {get; set;}
}
public class MyResponse
{
public List<PermittedItem> Permitted = new List<PermittedItems>();
}
然后像这样使用它:
MyResponse result = JsonConvert.DeserializeObject<MyResponse>(jsonAsString);
这应该有效。