【发布时间】:2019-02-11 14:18:05
【问题描述】:
我有这个 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]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 的答案,我能够验证和访问列表中的特定键和值。
【问题讨论】:
-
你的条目是什么?
-
为什么不反序列化为具体类型,让您的 C# 代码更易于编写和阅读?
-
你能反序列化到一个列表
- 吗?
-
你有
response这是一个对象。然后将其序列化为 JSON 字符串。然后将其反序列化为JArray。response的类型是什么,为什么不能直接从中获取数据? -
每当它推送一个新条目时都会获取计数值。