Harshad Chavan
Harshad Chavan

Reputation: 21

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. Property class which will be passed as a actual result with Ok Status with object. ( I am mocking actual requirement)

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.

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

My requirement is to have data in Json format with array as below -

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

Upvotes: 0

Views: 973

Answers (2)

Tcraw
Tcraw

Reputation: 274

=== Updated my answer to reflect clarified details ===

Solution with 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.

Here's an example using a dynamic JObject:

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

Upvotes: 0

Lei
Lei

Reputation: 528

using Newtonsoft.Json;

use this method to convert obj to string:

JsonConvert.SerializeObject(object)

use this method to convert string to obj:

JsonConvert.DeserializeObject(string)

Upvotes: 1

Related Questions