Reputation: 2157
I am constructing a JSON Body for the POST method for my Odata endpoint call like below
Newtonsoft.Json.Linq.JObject sample;
sample = new Newtonsoft.Json.Linq.JObject();
sample["status"] = "New";
sample[ "[email protected]"] = "["+"/PROJECT('" + prjBarcode + "')"+"]";
Where [email protected] is an array. I am looking that the JSON to be built like
"status": "New",
"[email protected]":["/PROJECT('PJ1')"]
But with my code above it is generating like
"[email protected]":"[/PROJECT('PJ1')]"
Where the []
comes with in the ""
how can I fix this
Upvotes: 1
Views: 250
Reputation: 118947
In JSON, square braces ([...]
) denote an array, so you need to create one, for example:
var array = new Newtonsoft.Json.Linq.JArray(new string[] {"/PROJECT('" + prjBarcode + "')" });
sample["[email protected]"] = array;
You should also consider using interpolated strings, it makes your code a lot more readable:
var array = new Newtonsoft.Json.Linq.JArray(new string[] {"/PROJECT('{prjBarcode}')" });
Though, I wouldn't be building up JSON like this in the first place. You should create a concrete type to do it that matches your structure and serialise it. For example:
public class Data
{
public string Status { get; set; }
[JsonProperty("[email protected]")]
public string[] Projects { get; set; }
}
var json = JsonConvert.SerializeObject(new Data
{
Status = "New",
Projects = new string[] {$"/PROJECT('{prjBarcode}')" }
});
Upvotes: 2
Reputation: 9632
You are passing string value for [email protected]
key and you just need to pass an array
sample[ "[email protected]"] = new JArray(new []{ "/PROJECT('" + prjBarcode + "')" });
or you can use another overload of JArray
constructor
sample[ "[email protected]"] = new JArray("/PROJECT('" + prjBarcode + "')");
Upvotes: 0