Reputation: 111
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Json;
namespace StackOverflowQuestion
{
class StackOverflowQuestion
{
public StackOverflowQuestion()
{
JsonObject jsonObj = new JsonObject();
string[] arr = { "first_value", "second_value", "third_value" };
obj.Add("array", arr ); // Compiler cannot convert string[] to System.Json.JsonValue
}
}
}
I want to receive in result Json object like
{"array":["first_value","second_value","third_value"]"}
Upvotes: 1
Views: 1323
Reputation: 17392
Create a wrapper class that you serialize that has an "Array" property. This will allow the JSON serialized object to have the "Array" field name you are looking for.
var array = { "first_value", "second_value", "third_value" };
var json = JsonConvert.SerializeObject(new JsonArray
{
Array = array,
Some_Field = true
});
public class JsonArray
{
public string[] Array { get; set; }
public bool Some_Field { get; set; }
}
Note, this uses Json.NET, which you can download/find more info about here: https://www.newtonsoft.com/json
Upvotes: 1
Reputation: 1441
Download/install NuGet package "Newtonsoft.Json" and then try this:
string[] arr = { "first_value", "second_value", "third_value"};
var json = JsonConvert.SerializeObject(arr);
So there is no Wrapper and so the json
-string is looking like this:
[
"first_value",
"second_value",
"third_value"
]
If you would use a warpper (Person.class) with data in it, it would look like this:
// Structure....
Person
private String name;
private String lastName;
private String[] arr; // for your example...
JsonConvert.SerializeObject(person);
{
"Person": {
"name": "<VALUE>",
"lastName": <VALUE>,
"arr":[
"first_value",
"second_value",
"third_value"
]
}
}
Upvotes: 0
Reputation: 743
You can use
JObject json = JObject.Parse(str);
Please refer this.
Upvotes: 0
Reputation: 2748
You can use JavaScriptSerializer
instead of declaring a JsonObject
string[] arr = { "first_value", "second_value", "third_value" };
new JavaScriptSerializer().Serialize(arr)
Upvotes: 0