1

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

4
  • 1
    What's the type of sample and how is json generated? Commented Feb 4, 2019 at 16:24
  • What is sample? Commented Feb 4, 2019 at 16:24
  • @Alexander Sorry I updated my question now Commented Feb 4, 2019 at 16:26
  • @DavidG I have updated my question Commented Feb 4, 2019 at 16:30

2 Answers 2

2

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

2 Comments

I am getting error Cannot implicitly convert type 'string[]' to 'Newtonsoft.Json.Linq.JToken'
Fixed, and added a better option.
0

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 + "')");

1 Comment

I am getting error Cannot implicitly convert type 'string[]' to 'Newtonsoft.Json.Linq.JToken'

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.