user2086641
user2086641

Reputation: 4371

Create JSON array with single key c#

I am working on VS2008 using .Net 3.5 framework. I am trying to create a JSON object with the below format,

{
  "types":["KKYQ","TGDF","YHGF"]
}

I tried the following code,

public class OutputJson
{
    public List<Types> types { get; set; }
}

public class Types
{
    public string types { get; set; }
}

public string getCodeTypes()
{
    foreach (var key in allKeys)
    {
        objToSerialize.Types.Add(new Types { types = key }); 
    }
    var objToSerialize = new OutputJson();
    var jsonOutput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(objToSerialize.types);
    string finalResposne = JsonConvert.SerializeObject(jsonOutput, Formatting.None);
    return jsonOutput.Replace(@"\", "");
}

The above code is producing the JSON in the below format,

"[{\"types\":\"KKYQ\"},{\"types\":\"TGDF\"},{\"types\":\"YHGF\"}]"

I googled and tried with some reference from google and i am not able to achieve the output in desired format.

Please help me in getting the JSON object in below format,

{
  "types":["KKYQ","TGDF","YHGF"]
}

Thanks for the help.

Upvotes: 1

Views: 4530

Answers (3)

John Wu
John Wu

Reputation: 52260

No class needed.

    Console.WriteLine
    (
        JsonConvert.SerializeObject
        (
            new 
            { 
                types = new [] { "KKYQ","TGDF","YHGF"}
            }
        )
    );

Output:

{"types":["KKYQ","TGDF","YHGF"]}

Link to Fiddle

Upvotes: 3

FaizanHussainRabbani
FaizanHussainRabbani

Reputation: 3439

No need to use a separate class for string property. Try following JSON object:

public class OutputJson
{
    public List<string> types { get; set; }
}

Using it like:

OutputJson json = new OutputJson
{
    types = new List<string> {"KKYQ", "TGDF", "YHGF"}
};
string finalResposne = JsonConvert.SerializeObject(json);

Or in your case:

var objToSerialize = new OutputJson();
foreach (var key in allKeys)
{
    objToSerialize.types.Add(key); 
}
string finalResposne = JsonConvert.SerializeObject(objToSerialize);

Output:

{
    "types": ["KKYQ", "TGDF", "YHGF"]
}

Upvotes: 4

see sharper
see sharper

Reputation: 12035

public class OutputJson
{
    public List<string> types { get; set; }
}

public string getCodeTypes()
{
    var objToSerialize = new OutputJson();
    foreach (var key in allKeys)
    {
        objToSerialize.Types.Add(key); 
    }   
    var jsonOutput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(objToSerialize);
    string finalResposne = JsonConvert.SerializeObject(jsonOutput, Formatting.None);
    return jsonOutput.Replace(@"\", "");
}

Upvotes: 1

Related Questions