验证值是否在具有相同键名的Json数组中

时间:2019-02-11 14:18:06

标签: c# arrays json

我有这个json正文

[
    {
        "Id": 1,
        "Name": "John",
        "Icon": "Icon/someplace",
        "SortOrder": 1
    },
    {
        "Id": 2,
        "Name": "Jessica",
        "Icon": "Icon/someplace",
        "SortOrder": 1
    },
    {
        "Id": 3,
        "Name": "Kevin",
        "Icon": "Icon/someplace",
        "SortOrder": 1
    },
    {
        "Id": 4,
        "Name": "Lint",
        "Icon": "Icon/someplace",
        "SortOrder": 1
    },
    {
       ...
    }
]

我正在通过API向json添加值,我需要验证新值存在于json正文中

我正在尝试隐蔽对json的响应,

public object Get_Json()
{
    var response = GEt_Json_Body();
    var json_string = JsonConvert.SerializeObject(response);
    JArray UpdatedContent = JArray.Parse(json_string);
    JObject Facility_Json = JObject.Parse(UpdatedContent[0].ToString());
    Assert.NotNull(Facility_Json);
    return Facility_Json;
}

这只会给我第一个json:

{
    "Id": 1,
    "Name": "John",
    "Icon": "Icon/someplace",
    "SortOrder": 1
}

UpdatedContent[i]我允许我获取数组中的其他json,问题是我不知道将使用API​​创建的json放在何处,如何获取所有JArray并验证我的条目在那里?

更新:

这是我的电话:

public List<FooModel> Get_Json_Body()
{
    var request = new RestRequest();
    request.Resource = string.Format("/api/get_something");

    return Execute<FooMedl>(request, Endpoint);
}

public  class FooModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Icon { get; set; }
    public int SortOrder { get; set; }
}


public List<T> Execute<T>(RestRequest request, string Endpoint) where T : new()
{

    Client.BaseUrl = new Uri(Endpoint);

    var response = Client.Execute<List<T>>(request);

    Console.WriteLine(response.ResponseUri);

    if (response.ErrorException != null)
    {
        string message = String.Format("Error retrieving response: \n{0} \n{1}  \n{2}  ",
            response.Content, response.ErrorMessage, response.ErrorException);

        Console.WriteLine(message);

        var exception = new ApplicationException(message);
        throw exception;
    }
    return Response.Data;
}

更新2:

Davig G的答案帮助我解决了该问题,能够通过以下方式验证我的输入

if(data.Any(f => f.Name == "Kevin"))
{
    Console.WriteLine("Kevin exists in the data");
}

我正在使用Get_Json()方法重现词典列表。使用DavigG的答案,我可以验证和访问列表中的特定键和值。

1 个答案:

答案 0 :(得分:2)

与纯JSON对象相比,处理具体类要容易得多,我建议直接将JSON反序列化为这样的对象列表:

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Icon { get; set; }
    public int SortOrder { get; set; }
}

反序列化的代码是:

var data = JsonConvert.DeserializeObject<List<Foo>>(response);

现在,您可以根据需要处理该对象,例如:

if(data.Any(f => f.Name == "Kevin"))
{
    Console.WriteLine("Kevin exists in the data");
}

甚至进行修改:

var kevin = data.SingleOrDefault(f => f.Name == "Kevin");
if(kevin != null)
{
    kevin.SortOrder = 3;
}

然后如果需要将其返回到原始JSON:

var json = JsonConvert.SerializeObject(data);