我如何在Json行中使用Foreach?

时间:2018-07-25 09:25:09

标签: c# asp.net api webforms restsharp

我在我的应用程序中使用RestSharp,我需要迭代代码中的某些部分。

request.AddParameter("undefined", "{\r\n    \"targetType\": \"SYSTEM\",\r\n    \"name\": \"xxxxxxxxxx\",\r\n    \"message\": \"Daily usage exceeded\",\r\n    \"active\": true,\r\n    \"emails\": [\"machin@truc.com\"],\r\n    \"conditions\": [{\r\n        \"operator\": \"EQUALS\",\r\n        \"operands\": [\r\n            {\r\n                \"attributeId\": \r\n                {\r\n                    \"name\": \"system.usage.status\"\r\n                }\r\n            \r\n            }, \r\n            {\r\n                \"valueStr\": \"nearing plan\"\r\n            }\r\n        ]\r\n    },\r\n    {\r\n        \"operator\": \"EQUALS\",\r\n        \"operands\": [\r\n            {\r\n                \"attributeId\": \r\n                {\r\n                    \"name\": \"system.name\"\r\n                }\r\n            \r\n            }, \r\n            {\r\n                \"valueStr\": \"SIM 89332401000006726968\"\r\n               \r\n            }\r\n        ]\r\n    },\r\n     {\r\n        \"operator\": \"EQUALS\",\r\n        \"operands\": [\r\n            {\r\n                \"attributeId\": \r\n                {\r\n                    \"name\": \"system.name\"\r\n                }\r\n            \r\n            }, \r\n            {\r\n                \"valueStr\": \"SIM 89332401000006726968\"\r\n               \r\n            }\r\n        ]\r\n    }\r\n    \r\n    ]\r\n}", ParameterType.RequestBody);

如何使用foreach迭代该部分?

 {\r\n        \"operator\": \"EQUALS\",\r\n        \"operands\": [\r\n            {\r\n                \"attributeId\": \r\n                {\r\n                    \"name\": \"system.name\"\r\n                }\r\n            \r\n            }, \r\n            {\r\n                \"valueStr\": \"SIM 89332401000006726968\"\r\n               \r\n            }\r\n        ]\r\n    }\r\n 

1 个答案:

答案 0 :(得分:1)

创建代表您的json结构的类,请向http://json2csharp.com/寻求帮助

public class AttributeId
{
    public string name { get; set; }
}

public class Operand
{
    public AttributeId attributeId { get; set; }
    public string valueStr { get; set; }
}

public class Condition
{
    public string @operator { get; set; }
    public List<Operand> operands { get; set; }
}

public class RootObject
{
    public string targetType { get; set; }
    public string name { get; set; }
    public string message { get; set; }
    public bool active { get; set; }
    public List<string> emails { get; set; }
    public List<Condition> conditions { get; set; }
}

之后,

var myJsonObject = JsonConvert.DeserializeObject<RootObject>(yourJsonString);

然后迭代myJsonObject.conditions