用 C# 制作 JSONP 文件

Posted

技术标签:

【中文标题】用 C# 制作 JSONP 文件【英文标题】:Make JSONP file in C# 【发布时间】:2018-04-04 07:05:21 【问题描述】:

我正在使用 C# 中的一个对象。

 public class City
   
      public int id  get; set; 
      public string label  get; set; 
   

我需要创建一个 JSONP 文件。我希望得到这样的东西

Places("id": 1, "label": "London", "id": 2, "label": "Paris")

我试过了

JsonSerializer serializer = new JsonSerializer();  ´
javascriptSerializer s = new JavaScriptSerializer();
using (StreamWriter file = File.CreateText("myJson.json"))

    serializer.Serialize(file, string.Format("0(1)", "Places", s.Serialize(places)));
    file.Close();

但我的结果文件是这样的:

"Places([\"id\":1,\"label\":\"London\", \"id\":2,\"label\":\"Paris\"])"

这个结果对我的'\"'字符不起作用

【问题讨论】:

Places("id": 1, "label": "London", "id": 2, "label": "Paris")not JSONP,因为它包含 2 个单独的 JSON 对象,没有包含数组。 请告诉我们您如何检查最终结果(包含\" 转义序列的结果)。 您对“JSONP 文件”的预期用途是什么?制作 JSONP 文件 将是 JSONP 的一种非常不寻常的用法。 我想把文件存到桶里 JSON 和 CORS 策略有什么问题? 【参考方案1】:

您将原始数据序列化为 JSON 两次,因此结果是包含字符串的 JSON,该字符串本身就是 JSON。

您应该简单地使用后缀/前缀对 JSON 进行字符串连接,例如 How can I manage ' in a JSONP response? 中所示:

var jsonpPrefix = "Places"  + "(";
var jsonpSuffix = ")";
var jsonp = 
    jsonpPrefix + 
    s.Serialize(places) + 
    jsonpSuffix);

将其写入文件的最简单方法就是File.WriteAllText("myJson.jsonp", jsonp)

也可以不先构造字符串,而是直接将其写入文件

using (StreamWriter sw = new StreamWriter("myJson.jsonp"))  

    sw.Write("Places(");
    sw.Write(s.Serialize(places));
    sw.Write(")"
  

旁注:将 JSONP 保存到文件有点奇怪,因为它通常只是作为对跨域 AJAX 请求的响应发送 - 所以请确保您确实需要 JSONP 而不仅仅是 JSON。

【讨论】:

以上是关于用 C# 制作 JSONP 文件的主要内容,如果未能解决你的问题,请参考以下文章

如何用c#(vs2005)制作留言板。

封装一个简单的JSONP

在 C# 程序中嵌入外部可执行文件

在 C# 程序中嵌入外部可执行文件

C#如何从json文件动态地制作treeview

JSONP