以 JSON 数组格式发送 class 数据以获取 ASP.Net Dot Core Web API 中的 GET 请求响应(从 Web API 获取响应数据)

Sending class data as JSON array format for GET request Response in ASP.Net Dot Core Web API ( GET response data from Web API)

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

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

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

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

我的要求是 Json 格式的数据,数组如下 -

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

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

JsonConvert.SerializeObject(object)

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

JsonConvert.DeserializeObject(string)

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

Json.Net的解决方案:

要获得您正在寻找的 JSON 结果,您需要创建自定义序列化程序或使用动态 JTokens 构建 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 Documentation - Create JSON w/ Dynamic