Nat
Nat

Reputation: 23

How to create exact JSON format to POST method in c# code?

Web Service required this format:

{
   "Data":"{\"Name\":\"HelloWorld\",\"BirthDate\":\"2020-03-03\",\"BirthPlace\":\"Nowhere\"}"
}

I required above format to post to web service but my code below doesn't fulfil the format. Please help. I've been using below code to post

 var Data = JsonConvert.SerializeObject(new
 {
    Data = new
    {
      Name= "HelloWorld",
      BirthDate = "2020-03-03",
      BirthPlace= "Nowhere"
    }
 });
 using (var client = new HttpClient())
 {
    HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, Data);
 }

Upvotes: 1

Views: 107

Answers (2)

Fildor
Fildor

Reputation: 16059

To get the required format do:

string name = "HelloWorld";
string birthdate = "2020-03-03";
string birthplace= "Nowhere";
var jsonData = JsonConvert.SerializeObject(new
{
    Data = $"\"Name\"=\"{name}\",\"BirthDate\"=\"{birthdate}\",\"BirthPlace\"=\"{birthplace}\""
});

See it in action: https://dotnetfiddle.net/UBXDtd

The format states that Data shall contain a string. Your code serializes an object with properties, which results in:

{"Data":{"Name":"HelloWorld","BirthDate":"2020-03-03","BirthPlace":"Nowhere"}}

EDIT: While this works, I would recommend @xdtTransform's answer over this. Leaving this here, in case his solution is for some reason not applicable.

Upvotes: 1

xdtTransform
xdtTransform

Reputation: 2057

If data should contains a string serialization of the real object. You can simply serialize the inner object using the string result as value on your second serialization.

using Newtonsoft.Json;

public static string WrapAndSerialize(object value){
    return JsonConvert.SerializeObject(new { Data = JsonConvert.SerializeObject(value) });  
}

Using it like:

var myObject= 
  new
  {
     Name = "HelloWorld",
     BirthDate = "2020-03-03", 
     BirthPlace = "Nowhere",
  };

var Data= WrapAndSerialize(myObject);
using (var client = new HttpClient())
{
    HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, Data);
}

LiveDemo

Upvotes: 1

Related Questions