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"]"}
1
  • 2
    Don't use JavaScriptSerializer. It's obsolete. Microsoft itself uses Json.NET Commented Oct 11, 2017 at 15:34

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Okay. But how to generate such json: {"some_field":true,"array":["first_value","second_value","third_value"]"}
0

You can use JavaScriptSerializer instead of declaring a JsonObject

string[] arr = { "first_value", "second_value", "third_value"          };
new JavaScriptSerializer().Serialize(arr)

Comments

0

You can use

 JObject json = JObject.Parse(str);

Please refer this.

Comments

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"
        ]
    }
}

Comments

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.