【问题标题】:Using JSON with VB.NET ASP.NET 2.0在 VB.NET ASP.NET 2.0 中使用 JSON
【发布时间】:2011-11-03 17:59:06
【问题描述】:

这里的所有新问题,我已经为此苦苦挣扎了好几个小时!

我正在尝试了解如何实际使用和创建 JSON 数据。我整个下午都在谷歌上搜索,并试图了解我在http://james.newtonking.com/projects/json/help/ 下载了 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 自动完成,我希望我可以编写一个简单的 SQL 查询并使用类似的东西返回它以上,但我显然是错的!

顺便说一句,上面的示例是用 C# 编写的,我已经成功地将过程转换为 VB,因为这就是我正在使用的,但任何响应都将非常感谢作为 VB 示例!

【问题讨论】:

    标签: vb.net json json.net


    【解决方案1】:

    我在这篇文章发布大约两年后才看到这篇文章,但我有完全相同的问题,并注意到这个问题并没有得到真正的回答。为了回答 OP 的问题,这将为您提供他示例中的 JSON 字符串。

    sb.toString()
    

    【讨论】:

      【解决方案2】:

      结果是您需要将 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
      

      在客户端,反序列化很简单:

          // The result should be a json-serialized record
          oRecord = Sys.Serialization.JavaScriptSerializer.deserialize(result.value);
      

      一旦你反序列化了对象,你就可以直接在javascript中使用它的属性:

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

      【讨论】:

      • 感谢@competent_tech 方便的信息。这有助于弄清楚我实际上要处理的过程是什么,现在我已经设法从上面的代码中获得 JSON 输出。但是,反序列化位不起作用,会出现各种错误,而我所做的任何更改都无法解决!我在想这是因为我使用的是 .NET 2.0 和 VB,谷歌搜索只是让我获得 C# 示例,而且我不是 100% 相信 .NET 2.0 支持内置序列化程序的效果如何
      【解决方案3】:

      在生成 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;
          }
      

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

      【讨论】:

      • 谢谢,那种看起来更简单,除了我使用的是 VB,但我想改变 VB 很容易。我终于设法让我的初始示例生成 JSON,但现在我正在努力用它做任何事情!请参阅下面我对 Competitive_tech 帖子的评论
      猜你喜欢
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 2014-09-26
      • 2021-01-07
      • 2012-06-03
      相关资源
      最近更新 更多