C# 如何在没有 JSON.NET 库的情况下解析 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9573119/
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 parse JSON without JSON.NET library?
提问by Eli Revah
I'm trying to build a Metro application for Windows 8 on Visual Studio 2011.
and while I'm trying to do that, I'm having some issues on how to parse JSONwithout JSON.NETlibrary (It doesn't support the metro applications yet).
我正在尝试在 Visual Studio 2011 上为 Windows 8 构建一个 Metro 应用程序。虽然我正在尝试这样做,但我在如何在JSON没有JSON.NET库的情况下进行解析时遇到了一些问题(它还不支持 Metro 应用程序) .
Anyway, I want to parse this:
无论如何,我想解析这个:
{
"name":"Prince Charming",
"artist":"Metallica",
"genre":"Rock and Metal",
"album":"Reload",
"album_image":"http:\/\/up203.siz.co.il\/up2\/u2zzzw4mjayz.png",
"link":"http:\/\/f2h.co.il\/7779182246886"
}
采纳答案by dtb
You can use the classes found in the System.Json Namespacewhich were added in .NET 4.5. You need to add a reference to the System.Runtime.Serializationassembly
您可以使用在System.Json 命名空间中找到的类,这些类是在 .NET 4.5 中添加的。您需要添加对System.Runtime.Serialization程序集的引用
The JsonValue.Parse() Methodparses JSON text and returns a JsonValue:
该JsonValue.Parse()方法解析JSON文本,并返回一个JsonValue:
JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");
If you pass a string with a JSON object, you should be able to cast the value to a JsonObject:
如果您传递带有 JSON 对象的字符串,您应该能够将该值转换为JsonObject:
using System.Json;
JsonObject result = value as JsonObject;
Console.WriteLine("Name .... {0}", (string)result["name"]);
Console.WriteLine("Artist .. {0}", (string)result["artist"]);
Console.WriteLine("Genre ... {0}", (string)result["genre"]);
Console.WriteLine("Album ... {0}", (string)result["album"]);
The classes are quite similar to those found in the System.Xml.Linq Namespace.
这些类与System.Xml.Linq Namespace 中的类非常相似。
回答by YS.
Have you tried using JavaScriptSerializer?
There's also DataContractJsonSerializer
你试过使用JavaScriptSerializer吗?还有DataContractJsonSerializer
回答by ctorx
I use this...but have never done any metro app development, so I don't know of any restrictions on libraries available to you. (note, you'll need to mark your classes as with DataContract and DataMember attributes)
我使用这个...但从未做过任何地铁应用程序开发,所以我不知道对您可用的库有任何限制。(注意,您需要将您的类标记为 DataContract 和 DataMember 属性)
public static class JSONSerializer<TType> where TType : class
{
/// <summary>
/// Serializes an object to JSON
/// </summary>
public static string Serialize(TType instance)
{
var serializer = new DataContractJsonSerializer(typeof(TType));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, instance);
return Encoding.Default.GetString(stream.ToArray());
}
}
/// <summary>
/// DeSerializes an object from JSON
/// </summary>
public static TType DeSerialize(string json)
{
using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(typeof(TType));
return serializer.ReadObject(stream) as TType;
}
}
}
So, if you had a class like this...
所以,如果你有这样的课程......
[DataContract]
public class MusicInfo
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Artist { get; set; }
[DataMember]
public string Genre { get; set; }
[DataMember]
public string Album { get; set; }
[DataMember]
public string AlbumImage { get; set; }
[DataMember]
public string Link { get; set; }
}
Then you would use it like this...
然后你会像这样使用它......
var musicInfo = new MusicInfo
{
Name = "Prince Charming",
Artist = "Metallica",
Genre = "Rock and Metal",
Album = "Reload",
AlbumImage = "http://up203.siz.co.il/up2/u2zzzw4mjayz.png",
Link = "http://f2h.co.il/7779182246886"
};
// This will produce a JSON String
var serialized = JSONSerializer<MusicInfo>.Serialize(musicInfo);
// This will produce a copy of the instance you created earlier
var deserialized = JSONSerializer<MusicInfo>.DeSerialize(serialized);
回答by TheBoyan
回答by toddmo
For those who do not have 4.5, Here is my library function that reads json. It requires a project reference to System.Web.Extensions.
对于那些没有 4.5 的人,这是我读取 json 的库函数。它需要对System.Web.Extensions.
using System.Web.Script.Serialization;
public object DeserializeJson<T>(string Json)
{
JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer();
return JavaScriptSerializer.Deserialize<T>(Json);
}
Usually, json is written out based on a contract. That contract can and usually will be codified in a class (T). Sometimes you can take a word from the json and search the object browser to find that type.
通常,json 是基于契约写出来的。该合同可以并且通常会被编入一个类 ( T) 中。有时您可以从 json 中提取一个词并搜索对象浏览器以找到该类型。
Example usage:
用法示例:
Given the json
鉴于json
{"logEntries":[],"value":"My Code","text":"My Text","enabled":true,"checkedIndices":[],"checkedItemsTextOverflows":false}
You could parse it into a RadComboBoxClientStateobject like this:
您可以将其解析为这样的RadComboBoxClientState对象:
string ClientStateJson = Page.Request.Form("ReportGrid1_cboReportType_ClientState");
RadComboBoxClientState RadComboBoxClientState = DeserializeJson<RadComboBoxClientState>(ClientStateJson);
return RadComboBoxClientState.Value;

