在VB.NET ASP.NET 2.0中使用JSON

在VB.NET ASP.NET 2.0中使用JSON,vb.net,json,json.net,Vb.net,Json,Json.net,这是一个全新的问题,我已经挣扎了好几个小时了 我试图理解如何实际使用和创建JSON数据。我整个下午都在谷歌上搜索,试图了解下载了Newtonsoft DLL后我在这里的感受 StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = F

这是一个全新的问题,我已经挣扎了好几个小时了

我试图理解如何实际使用和创建JSON数据。我整个下午都在谷歌上搜索,试图了解下载了Newtonsoft DLL后我在这里的感受

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;

jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("CPU");
jsonWriter.WriteValue("Intel");
jsonWriter.WritePropertyName("PSU");
jsonWriter.WriteValue("500W");
jsonWriter.WritePropertyName("Drives");
jsonWriter.WriteStartArray();
jsonWriter.WriteValue("DVD read/writer");
jsonWriter.WriteComment("(broken)");
jsonWriter.WriteValue("500 gigabyte hard drive");
jsonWriter.WriteValue("200 gigabype hard drive");
jsonWriter.WriteEnd();
jsonWriter.WriteEndObject();
}
应该创建如下内容:

{
   "CPU": "Intel",
   "PSU": "500W",
   "Drives": [
   "DVD read/writer"
    /*(broken)*/,
     "500 gigabyte hard drive",
     "200 gigabype hard drive"      ]
}
我相信它确实。。。但我怎么看呢?如何将其转换为浏览器可以输出的对象

在我看来,我需要解决的第一个阶段是“如何创建”JSON文件/字符串,下一个阶段将是如何实际使用它们。如果这有助于回答这个问题,我最初的目标是能够从MySQL数据库生成的搜索页面中使用AJAX Autocomplete,我希望我可以编写一个简单的SQL查询,并使用类似于上面的内容返回,但我显然是完全错了


顺便说一句,上面的例子是C#,我已经成功地将这个过程转换为VB,因为这就是我正在使用的,但是任何回应都将被视为VB示例

结果是您需要将JSON字符串返回到浏览器。您可以将其放置在javascript变量中(如果这样做,请确保清除行结束符和单引号),也可以将其作为ajax查询的结果传回

我们实际上使用内置的Javascript序列化程序,因为它在服务器端和客户端都有支持,并且非常容易使用。假设您有一个现有对象,则以下代码将在服务器端执行:

''' <summary>
''' This method safely serializes an object for JSON by removing all of the special characters (i.e. CRLFs, quotes, etc)
''' </summary>
''' <param name="oObject"></param>
''' <param name="fForScript">Set this to true when the JSON will be embedded directly in web page (as opposed to being passed through an ajax call)</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function SerializeObjectForJSON(ByVal oObject As Object, Optional ByVal fForScript As Boolean = False) As String

If oObject IsNot Nothing Then
    Dim sValue As String

    sValue = (New System.Web.Script.Serialization.JavaScriptSerializer).Serialize(oObject)

    If fForScript Then
        ' If this serialized object is being placed directly on the page, then we need to ensure that its CRLFs are not interpreted literlally (i.e. as the actual JS values)
        ' If we don't do this, the script will not deserialize correctly if there are any embedded crlfs.
        sValue = sValue.Replace("\r\n", "\\r\\n")

        ' Fix quote marks
        Return CleanString(sValue)
    Else
        Return sValue
    End If
Else
    Return String.Empty
End If
End Function
反序列化对象后,可以直接在javascript中使用其属性:

alert('CPU = ' + oRecord.CPU);

在生成JSON方面,请尝试

    public class HardwareInfo
    {
        [JsonProperty(PropertyName = "CPU")]
        public string Cpu { get; set; }
        [JsonProperty(PropertyName = "PSU")]
        public string Psu { get; set; }
        [JsonProperty]
        public ICollection<string> Drives { get; set; }
    }

    public string SerializeHardwareInfo()
    {
        var info = new HardwareInfo
        {
            Cpu = "Intel",
            Psu = "500W",
            Drives = new List<string> { "DVD read/writer", "500 gigabyte hard drive", "200 gigabype hard drive" }
        };

        var json = JsonConvert.SerializeObject(info, Formatting.Indented);
        //  {
        //    "CPU": "Intel",
        //    "PSU": "500W",
        //    "Drives": [
        //      "DVD read/writer",
        //      "500 gigabyte hard drive",
        //      "200 gigabype hard drive"
        //    ]
        //  }
        return json;
    }
公共类硬件信息
{
[JsonProperty(PropertyName=“CPU”)]
公共字符串Cpu{get;set;}
[JsonProperty(PropertyName=“PSU”)]
公共字符串Psu{get;set;}
[JsonProperty]
公用ICollection驱动器{get;set;}
}
公共字符串序列化HardwareInfo()
{
var info=新硬件信息
{
Cpu=“英特尔”,
Psu=“500W”,
驱动器=新列表{“DVD读/写器”、“500 GB硬盘驱动器”、“200 GB硬盘驱动器”}
};
var json=JsonConvert.serialized对象(info,Formatting.Indented);
//  {
//“CPU”:“英特尔”,
//“PSU”:“500W”,
//“驱动器”:[
//“DVD读/写器”,
//“500 GB硬盘驱动器”,
//“200千兆字节硬盘驱动器”
//    ]
//  }
返回json;
}

格式化参数是可选的。祝你好运。

这篇文章发布两年后,我偶然发现了它,但我有一个完全相同的问题,并注意到这个问题并没有得到真正的回答。为了回答OP的问题,这将得到他的示例中的JSON字符串

sb.toString()

谢谢,这样看起来比较简单,除了我用的是VB,但是我想用VB修改它很容易。我终于成功地获得了生成JSON的初始示例,但现在我在用它做任何事情时都举步维艰!请参阅我对Competable_tech帖子的评论,网址为hanks@competable_tech handy info。这有助于澄清我试图处理的过程实际上是什么,现在我已经设法从上面的代码中获得JSON输出。反序列化位将不起作用,但是,得到各种各样的错误,无论我更改什么都不能修复它!我认为这是因为我使用的是.NET2.0和VB,谷歌搜索只是给了我一些C#示例,我并不完全相信.NET2.0对内置序列化程序的支持有多好
sb.toString()