java 在 .NET Framework 中创建 JSONObject 的库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16054494/
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
Library to Create a JSONObject in .NET Framework
提问by Matthew
I am looking for a JSON library which is able to do the following:
我正在寻找一个能够执行以下操作的 JSON 库:
PC 1
电脑 1
JSONObject obj = new JSONObject();
obj.put("name", "mkyong.com");
obj.put("age", new Integer(100));
PC 2
电脑 2
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);
As you can see, there was no need to create a class in order to send the name and age value pairs. Now, this code is in Java. Is there a library in .NET which does this? I checked the documentation for JSON.NET, however it appears that it does not offer the use of a JSONobject where we can add value pairs.
如您所见,无需创建类即可发送名称和年龄值对。现在,这段代码是用 Java 编写的。.NET 中有一个库可以做到这一点吗?我检查了 JSON.NET 的文档,但是它似乎没有提供 JSONobject 的使用,我们可以在其中添加值对。
回答by I4V
You can use Json.Net
您可以使用Json.Net
dynamic jsonObject = new JObject();
jsonObject.Name = "mkyong.com";
jsonObject.Age = 100;
var json = jsonObject.ToString();
output:
输出:
{
"Name": "mkyong.com",
"Age": 100
}
or without dynamic
或没有 dynamic
JObject jsonObject = new JObject();
jsonObject["Name"] = "mkyong.com";
jsonObject["Age"] = 100;
var json = jsonObject.ToString();
You can even make use of anonymous classes
你甚至可以使用匿名类
var json = JsonConvert.SerializeObject(new {Name="mkyong.com", Age=100 });