Reputation: 103
How can I create this JSON string in C#? If I don't want to create a ViewModel to serialize with Json.NET, is there any other way?
Please refer to the JSON string below:
{
"1": { "1年期": "12", "13個月期": "13", "2年期": "24", "3年期": "36"},
"2": { "1年期": "12", "13個月期": "13", "2年期": "24", "3年期": "36"},
"3": { "1個月期": "1", "3個月期": "3", "6個月期": "6", "9個月期": "9", "1年期": "12", "13個月期": "13", "2年期": "24", "3年期": "36" }
};
Upvotes: 0
Views: 118
Reputation: 103
Here is another answer to share...
JObject obj_1 = new JObject(
new JProperty("12", "1年期"),
new JProperty("13", "13個月期"),
new JProperty("24", "2年期"),
new JProperty("36", "3年期")
);
JObject obj_2 = new JObject(
new JProperty("12", "1年期"),
new JProperty("13", "13個月期"),
new JProperty("24", "2年期"),
new JProperty("36", "3年期")
);
JObject obj_3 = new JObject(
new JProperty("1", "1個月期"),
new JProperty("3", "3個月期"),
new JProperty("6", "6個月期"),
new JProperty("9", "9個月期"),
new JProperty("12", "1年期"),
new JProperty("13", "13個月期"),
new JProperty("24", "2年期"),
new JProperty("36", "3年期")
);
JObject objectParent = new JObject();
objectParent.Add("1", obj_1);
objectParent.Add("2", obj_2);
objectParent.Add("3", obj_3);
Upvotes: 1
Reputation: 129667
You can use a Dictionary<string, Dictionary<string, string>>
to create the JSON. First set up the dictionary with the data you want, then return it from your MVC controller using the Json()
method like this:
public ActionResult GetMyJson()
{
var dict = new Dictionary<string, Dictionary<string, string>>()
{
{
"1", new Dictionary<string, string>()
{
{ "1年期", "12" },
{ "13個月期", "13" },
{ "2年期", "24" },
{ "3年期", "36" },
}
},
{
"2", new Dictionary<string, string>()
{
{ "1年期", "12" },
{ "13個月期", "13" },
{ "2年期", "24" },
{ "3年期", "36" },
}
},
{
"3", new Dictionary<string, string>()
{
{ "1個月期", "1" },
{ "3個月期", "3" },
{ "6個月期", "6" },
{ "9個月期", "9" },
{ "1年期", "12" },
{ "13個月期", "13" },
{ "2年期", "24" },
{ "3年期", "36" },
}
}
};
return Json(dict);
}
Alternatively, you can serialize the dictionary using Json.Net like this:
string json = JsonConvert.SerializeObject(dict, Formatting.Indented);
But if you do it this way, and you want to return the JSON from inside an MVC controller, you will need to use the Content()
method instead:
return Content(json, "application/json");
Upvotes: 1