简体   繁体   English

Sending class data as JSON array format for GET request Response in ASP.Net Dot Core Web API ( GET response data from 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)

I am writing a Web API with requirement where need to pass result class property values as array of Json in response of GET request.我正在写一个 Web API ,其中需要将结果 class 属性值作为 ZEED8D85B888A6C03353Z4 响应的数组传递给请求。 Property class which will be passed as a actual result with Ok Status with object.属性 class 将作为实际结果通过 object 的 Ok 状态。 ( I am mocking actual requirement) (我是mocking实际需求)

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

I am following default JSONfor matter option which are available in dotnet core web api and it is converting all class attribute into single json element.我正在关注 dotnet 核心 web api 中可用的默认 JSONfor 问题选项,它将所有 class 属性转换为单个 Z4666DEEC7F6ECDF25DAD6487 元素。

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

My requirement is to have data in Json format with array as below -我的要求是拥有 Json 格式的数据,数组如下 -

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

use this method to convert obj to string:使用此方法将 obj 转换为字符串:

JsonConvert.SerializeObject(object)

use this method to convert string to obj:使用此方法将字符串转换为 obj:

JsonConvert.DeserializeObject(string)

=== Updated my answer to reflect clarified details === === 更新了我的答案以反映明确的细节 ===

Solution with Json.Net: Json.Net 的解决方案:

To get the JSON result that you're looking for, you'll need to create a custom serializer or build your JSON object with dynamic JTokens.要获得您正在寻找的 JSON 结果,您需要创建自定义序列化程序或使用动态 JToken 构建 JSON object。

Here's an example using a dynamic JObject:下面是一个使用动态 JObject 的示例:

https://dotnetfiddle.net/EyL5Um https://dotnetfiddle.net/EyL5Um

Code:代码:

// 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());

Note笔记

In this form, the code above is not a scalable solution.在这种形式下,上面的代码不是一个可扩展的解决方案。 But it should provide you with a starting point to then build up an iterative approach for the data you're working with.但它应该为您提供一个起点,然后为您正在使用的数据建立一种迭代方法。

References参考

Newtonsoft Documentation - Create JSON w/ Dynamic Newtonsoft 文档 - 使用动态创建 JSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM