0

我有一个 Ext.data.TreeStore 从文本文件中读取数据:

在此处输入图像描述

this.store = Ext.create('Ext.data.TreeStore', {
        model: "GeoExt.data.LayerTreeModel",
        proxy: new Ext.data.HttpProxy({
            url: 'data/test.json',
            reader: {
                type: 'json',
                root: 'children',
                idProperty: 'Id'
            }
        }),
        folderSort: true
    });

这是文件内容:

[
    {
        text: "Category1",
        leaf: false,
        expanded: true,
        checked: false,
        children: [
            {
                text: "A1",
                layer: "A2",
                name: "A3",
                leaf: true,
                checked: false,
                nodeType: "gx_layer"
            },
            {
                text: "B1",
                layer: "B2",
                name: "B3",
                leaf: true,
                checked: false,
                nodeType: "gx_layer"
            }
            ],
        nodeType: "gx_layer"
    },
    {
        text: "Category2",
        leaf: false,
        expanded: true,
        checked: false,
        children: [
            {
                text: "C1",
                layer: "C2",
                name: "C3",
                leaf: true,
                checked: false,
                nodeType: "gx_layer"
            }],
        nodeType: "gx_layer"
    }
]

我在 firebug 中注意到 get 不返回 JSON struct ,而是纯文本。但它有效。

在此处输入图像描述

我想得到相同的结果,但从 web 服务中获取树节点(这将它从 postgres 中带回来)。

我尝试的第一个最简单的事情是(也尝试过 text/json):

[WebMethod]        
        public void GetJSON()
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "text/plain";
            HttpContext.Current.Response.Charset = "utf-8";

            string res = File.ReadAllText(@"D:\test.json");
            HttpContext.Current.Response.Write(res);
        }     

我收到错误:

Request format is unrecognized for URL unexpectedly ending in '/getJSON'.

这是有道理的,因为该文件不是 JSON(但这就是我设法使其工作的方式)。

我想帮助解决两件事:

  1. 我需要使用什么正确的 JSON 格式来获得与本示例中相同的结果?
  2. 如何从 webservice 提供相同的数据?

谢谢 !

***************** 解决方案 ******************

根据 Meister 的回答,该方法需要如下所示:

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]       
public void GetJSON()
{
Object res = new Object();
JavaScriptSerializer js = new JavaScriptSerializer();
string str = js.Serialize(res);
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.AddHeader("content-disposition", "attachment; filename=export.json");
Context.Response.Flush();
Context.Response.Write(str);
} 
4

1 回答 1

0

您可以尝试替换:

HttpContext.Current.Response.ContentType = "text/plain";

有了这个:

HttpContext.Current.Response.ContentType = "application/json";

更新: 您还可以尝试[ScriptService]在 Web 服务类之上添加。

无论如何,我认为从 Web 服务读取 JSON 文件是没有意义的。您可以像在第一个代码示例中那样从 JSON 阅读器中读取它。我使用 Web 服务来处理传递的参数并制作一些东西(如 JSON 对象)来响应。

于 2013-10-31T02:49:01.823 回答