0

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

2 Answers 2

1
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)
Sign up to request clarification or add additional context in comments.

Comments

0

=== 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

3 Comments

Corrected My question , I have to send back response as JSON array. And I tried using list and adding a class to it. Unfortunately it behaves in same way as I described for my question.
Thank you for the clarification. Updated my answer.
Thanks for your time and help ! Still it is not having name in separate element and Address in a separate ( I mean separate curly braces { } ) .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.