QigangZhong
QigangZhong

Reputation: 21

how to generate json string with an integer as key?

I want to generate json string like this in C# language

{
  "error": "0",
  "message": "messages",
  "data": {
    "version": "sring",
    "1": [
      {
        "keyword": "",
        "title": ""
      },
      {
        "keyword": "",
        "title": ""
      }
    ],
    "2": [
      ...
    ],
    "3": [
      ...
    ]
  }
}

there is a problem here, "1":[{},{}],how to generate this part? I'm using asp.net mvc project by the way, I want to return this json string to the client web browser.

Upvotes: 2

Views: 6560

Answers (4)

Kayani
Kayani

Reputation: 972

Get the Json.NET from NuGet. Then, in your MVC model use this data annotation on your Array property

[JsonProperty(PropertyName="1")]
public string[] YourProperty { get; set }

The PropertyName value is used when you serialize data to JSON.

Upvotes: 5

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34234

This response can be simply generated using Dictionary<string, object> with arrays as values.

public class KeywordTitle
{
    public string keyword { get; set; }
    public string title { get; set; }
}

public class Response
{
    public string error { get; set; }
    public string message { get; set; }
    public Dictionary<string, object> data { get; set; }
}

var dictionary = new Dictionary<string, object> {
    {"version", "sring"}
};

dictionary.Add("1", new []
{
    new KeywordTitle { keyword = "", title = "" },
    new KeywordTitle { keyword = "", title = "" },
    new KeywordTitle { keyword = "", title = "" }
});

JsonConvert.SerializeObject(new Response
{
    error = "0",
    message = "messages",
    data = dictionary
});

It generates:

{
    "error" : "0",
    "message" : "messages",
    "data" : {
        "version" : "sring",
        "1" : [{
                "keyword" : "",
                "title" : ""
            }, {
                "keyword" : "",
                "title" : ""
            }, {
                "keyword" : "",
                "title" : ""
            }
        ]
    }
}

If it is your API, then it is a good idea to extract version in order to make all objects in data be of the same type, and keys of type int.

Upvotes: 8

user449689
user449689

Reputation: 3154

Use Json.net and add the following attribute to the properties you what to modify the name of:

[JsonProperty(PropertyName = "1")]
public List<ObjectName> Objects { get; set; }

For more information have a look at the serialization attributes.

Upvotes: 0

If you are using Newtonsoft.Json NuGet package, serializing a Dictionary<int, List<MyClass>> will get you what you the expected result.

Upvotes: 3

Related Questions