1
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"]"}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
J. Huxley
  • 111
  • 2

4 Answers4

1

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

d.moncada
  • 16,900
  • 5
  • 53
  • 82
  • Okay. But how to generate such json: {"some_field":true,"array":["first_value","second_value","third_value"]"} – J. Huxley Oct 11 '17 at 15:45
0

You can use JavaScriptSerializer instead of declaring a JsonObject

string[] arr = { "first_value", "second_value", "third_value"          };
new JavaScriptSerializer().Serialize(arr)
GGO
  • 2,678
  • 4
  • 20
  • 42
0

You can use

 JObject json = JObject.Parse(str);

Please refer this.

Sandeep P Pillai
  • 753
  • 1
  • 4
  • 22
0

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"
        ]
    }
}
LenglBoy
  • 1,451
  • 1
  • 10
  • 24