【问题标题】:Sending class data as JSON array format for GET request Response in ASP.Net Dot Core Web API ( GET response data from Web API)在 ASP.Net Dot Core Web API 中以 JSON 数组格式发送类数据以获取请求响应(从 Web API 获取响应数据)
【发布时间】:2020-07-03 13:10:19
【问题描述】:

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

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"}
             ]
   }

【问题讨论】:

    标签: c# .net-core asp.net-core-webapi webapi


    【解决方案1】:
    using Newtonsoft.Json;
    

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

    JsonConvert.SerializeObject(object)
    

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

    JsonConvert.DeserializeObject(string)
    

    【讨论】:

      【解决方案2】:

      === 更新了我的答案以反映明确的细节 ===

      使用 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 Documentation - Create JSON w/ Dynamic

      【讨论】:

      • 更正了我的问题,我必须将响应作为 JSON 数组发回。我尝试使用列表并为其添加一个类。不幸的是,它的行为方式与我为我的问题描述的方式相同。
      • 感谢您的澄清。更新了我的答案。
      • 感谢您的宝贵时间和帮助!它仍然没有单独的元素中的名称和单独的地址(我的意思是单独的花括号 { } )。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 2017-10-19
      相关资源
      最近更新 更多