如何使用 C# 创建我的 json 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14828520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create my json string by using C#?
提问by Saravanan
I am new to json format. I want to create a following json string by using C# and json.net package.
我是 json 格式的新手。我想使用 C# 和 json.net 包创建以下 json 字符串。
This is my target Json format:
这是我的目标 Json 格式:
{
"GetQuestions":
{
"s1":"Q1,Q2",
"s2":"Q1,Q3",
"s3":"Q4,Q5"
}
}
Here, i am storing each students questions.But sometimes, the total number of students may be vary.for example it may be s1,s2 only or s1,s2,s3,s4.... This is calculated at runtime in C#.So, i want to create the json string depending on the student list....
在这里,我正在存储每个学生的问题。但有时,学生总数可能会有所不同。例如,它可能只是 s1,s2 或 s1,s2,s3,s4.... 这是在 C# 中在运行时计算的。所以,我想根据学生名单创建json字符串....
Please guide me to get out of this issue?
请指导我摆脱这个问题?
采纳答案by jjchiw
The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....
json有点奇怪,就像学生是“GetQuestion”对象的属性一样,应该很容易成为一个列表.....
About the libraries you could use are.
关于您可以使用的库是。
And there could be many more, but that are what I've used
可能还有更多,但这就是我用过的
About the json I don't now maybe something like this
关于 json 我现在不知道可能是这样的
public class GetQuestions
{
public List<Student> Questions { get; set; }
}
public class Student
{
public string Code { get; set; }
public string Questions { get; set; }
}
void Main()
{
var gq = new GetQuestions
{
Questions = new List<Student>
{
new Student {Code = "s1", Questions = "Q1,Q2"},
new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
}
};
//Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
JsonConvert.SerializeObject(gq).Dump();
}
and the result is this
结果是这样的
{
"Questions":[
{"Code":"s1","Questions":"Q1,Q2"},
{"Code":"s2","Questions":"Q1,Q2,Q3"},
{"Code":"s3","Questions":"Q1,Q2,Q4"},
{"Code":"s4","Questions":"Q1,Q2,Q5"}
]
}
Yes I know the json is different, but the json that you want with dictionary.
是的,我知道 json 是不同的,但是您需要字典的 json。
void Main()
{
var f = new Foo
{
GetQuestions = new Dictionary<string, string>
{
{"s1", "Q1,Q2"},
{"s2", "Q1,Q2,Q3"},
{"s3", "Q1,Q2,Q4"},
{"s4", "Q1,Q2,Q4,Q6"},
}
};
JsonConvert.SerializeObject(f).Dump();
}
class Foo
{
public Dictionary<string, string> GetQuestions { get; set; }
}
And with Dictionary is as you want it.....
和字典是你想要的......
{
"GetQuestions":
{
"s1":"Q1,Q2",
"s2":"Q1,Q2,Q3",
"s3":"Q1,Q2,Q4",
"s4":"Q1,Q2,Q4,Q6"
}
}
回答by Grant Thomas
No real need for the JSON.NET package. You could use JavaScriptSerializer
. The Serialize
methodwill turn a managed type instance into a JSON string.
不需要 JSON.NET 包。你可以使用JavaScriptSerializer
. 该Serialize
方法会将托管类型实例转换为 JSON 字符串。
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);
回答by fibertech
To convert any object or object list into JSON, we have to use the function JsonConvert.SerializeObject.
要将任何对象或对象列表转换为 JSON,我们必须使用 JsonConvert.SerializeObject 函数。
The below code demonstrates the use of JSON in an ASP.NET environment:
下面的代码演示了 JSON 在 ASP.NET 环境中的使用:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace JSONFromCS
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e1)
{
List<Employee> eList = new List<Employee>();
Employee e = new Employee();
e.Name = "Minal";
e.Age = 24;
eList.Add(e);
e = new Employee();
e.Name = "Santosh";
e.Age = 24;
eList.Add(e);
string ans = JsonConvert.SerializeObject(eList, Formatting.Indented);
string script = "var employeeList = {\"Employee\": " + ans+"};";
script += "for(i = 0;i<employeeList.Employee.length;i++)";
script += "{";
script += "alert ('Name : ='+employeeList.Employee[i].Name+'
Age : = '+employeeList.Employee[i].Age);";
script += "}";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(Page.GetType(), "JSON", script, true);
}
}
public class Employee
{
public string Name;
public int Age;
}
}
After running this program, you will get two alerts
运行此程序后,您将收到两个警报
In the above example, we have created a list of Employee object and passed it to function "JsonConvert.SerializeObject". This function (JSON library) will convert the object list into JSON format. The actual format of JSON can be viewed in the below code snippet:
在上面的示例中,我们创建了一个 Employee 对象列表并将其传递给函数“JsonConvert.SerializeObject”。此函数(JSON 库)将对象列表转换为 JSON 格式。JSON 的实际格式可以在下面的代码片段中查看:
{ "Maths" : [ {"Name" : "Minal", // First element
"Marks" : 84,
"age" : 23 },
{
"Name" : "Santosh", // Second element
"Marks" : 91,
"age" : 24 }
],
"Science" : [
{
"Name" : "Sahoo", // First Element
"Marks" : 74,
"age" : 27 },
{
"Name" : "Santosh", // Second Element
"Marks" : 78,
"age" : 41 }
]
}
Syntax:
句法:
{} - acts as 'containers'
[] - holds arrays
: - Names and values are separated by a colon
, - Array elements are separated by commas
{} - 充当“容器”
[] - 保存数组
: - 名称和值由冒号分隔
, - 数组元素用逗号分隔
This code is meant for intermediate programmers, who want to use C# 2.0 to create JSON and use in ASPX pages.
此代码适用于希望使用 C# 2.0 创建 JSON 并在 ASPX 页面中使用的中级程序员。
You can create JSON from JavaScript end, but what would you do to convert the list of object into equivalent JSON string from C#. That's why I have written this article.
您可以从 JavaScript 端创建 JSON,但是您将如何将对象列表从 C# 转换为等效的 JSON 字符串。这就是我写这篇文章的原因。
In C# 3.5, there is an inbuilt class used to create JSON named JavaScriptSerializer.
在 C# 3.5 中,有一个内置类用于创建名为 JavaScriptSerializer 的 JSON。
The following code demonstrates how to use that class to convert into JSON in C#3.5.
以下代码演示了如何使用该类在 C#3.5 中转换为 JSON。
JavaScriptSerializer serializer = new JavaScriptSerializer()
return serializer.Serialize(YOURLIST);
So, try to create a List of arrays with Questions and then serialize this list into JSON
因此,尝试使用 Questions 创建一个数组列表,然后将此列表序列化为 JSON