如何返回JSON对象 [英] How to return JSon object
问题描述
我使用的是jQuery插件,需要一个JSON对象具有以下结构(我会从检索数据库中的值):
I am using a jQuery plugin that need a JSON object with following structure(I will be retrieving the values from database):
{ results: [
{ id: "1", value: "ABC", info: "ABC" },
{ id: "2", value: "JKL", info: "JKL" },
{ id: "3", value: "XYZ", info: "XYZ" }
] }
下面是我的类:
public class results
{
int _id;
string _value;
string _info;
public int id
{
get
{
return _id;
}
set
{
_id = value;
}
}
public string value
{
get
{
return _value;
}
set
{
_value = value;
}
}
public string info
{
get
{
return _info;
}
set
{
_info = value;
}
}
}
这是我序列的方式:
results result = new results();
result.id = 1;
result.value = "ABC";
result.info = "ABC";
string json = JsonConvert.SerializeObject(result);
但是,这将只返回一行。能否请你帮我返回不止一个结果?我怎样才能得到的结果在上述指定的格式?
But this will return only one row. Can you please help me in returning more than one result? How can I get the result in the format specified above?
推荐答案
首先,有的没有这样的东西作为一个JSON对象。你已经得到了你的问题是一个JavaScript对象文字(请参阅here有关差异的大讨论)。这里是你将如何去序列化,你得JSON虽然什么:
First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:
我会用匿名类型充满了你的结果
类型:
I would use an anonymous type filled with your results
type:
string json = JsonConvert.SerializeObject(new
{
results = new List<Result>()
{
new Result { id = 1, value = "ABC", info = "ABC" },
new Result { id = 2, value = "JKL", info = "JKL" }
}
});
此外,请注意,生成的JSON与 ID
S型编号
而不是字符串的结果项目。我怀疑这将是一个问题,但它会很容易 ID
的类型更改为字符串
在C#。
Also, note that the generated JSON has result items with id
s of type Number
instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id
to string
in the C#.
我也想调整你的结果
键入和摆脱后盾字段:
I'd also tweak your results
type and get rid of the backing fields:
public class Result
{
public int id { get ;set; }
public string value { get; set; }
public string info { get; set; }
}
此外,传统的类是 PascalCased
,而不是驼峰格式
。
下面从上面的code是生成的JSON:
Here's the generated JSON from the code above:
{
"results": [
{
"id": 1,
"value": "ABC",
"info": "ABC"
},
{
"id": 2,
"value": "JKL",
"info": "JKL"
}
]
}
这篇关于如何返回JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!