将类数据作为 JSON 数组格式发送,用于 GET 请求 ASP.Net Dot Core Web API 中的响应(来



我正在编写一个 Web API,需要将结果类属性值作为 JSON 数组传递以响应 GET 请求。 属性类,它将作为实际结果传递,带有对象的 Ok 状态。(我在嘲笑实际需求(

public class ABC
{
public string Name {get;set;}
public string Address{get;set;}
}

我正在遵循dotnet core web api中可用的默认JSONfor matter选项,它将所有类属性转换为单个json元素。

{
"Person" : 
[
{
"Name": "ABCD",
"Address": "INDIA"
}
]
}

我的要求是拥有带有如下数组的 Json 格式数据 -

{
"Person" : 
[
{"Name": "ABCD"},
{"Address": "INDIA"}
]
}
using Newtonsoft.Json;

使用此方法将 OBJ 转换为字符串:

JsonConvert.SerializeObject(object)

使用此方法将字符串转换为 OBJ:

JsonConvert.DeserializeObject(string)

=== 更新了我的答案以反映澄清的细节 ===

带 Json.Net 的解决方案:

若要获取所需的 JSON 结果,需要创建自定义序列化程序或使用动态 JToken 生成 JSON 对象。

下面是一个使用动态 JObject 的示例:

https://dotnetfiddle.net/EyL5Um

法典:

// Create sample object to serialize
var person = new ABC() { Name = "ABC",  Address = "India" };

// Build JSON with dynamic JTokens
dynamic jsonObj = new JObject();

var token = new JArray();
token.Add(new JObject(
new JProperty("Name", person.Name)));
token.Add(new JObject(
new JProperty("Address", person.Address)));
jsonObj.Person = token;

// Print result to console
Console.WriteLine(jsonObj.ToString());

注意

在这种形式中,上面的代码不是可扩展的解决方案。但它应该为您提供一个起点,然后为您正在使用的数据构建迭代方法。

引用

Newtonsoft 文档 - 创建带动态的 JSON

最新更新