Windows8解析Json

发布于 2025-01-01 07:24:37 字数 3188 浏览 2 评论 0原文

我尝试了多种方法在 Windows 8 中解析 json,但我经常收到此错误。

“WinRT 信息:WEB_E_INVALID_JSON_STRING”

我使用相同的 json 字符串,如果我从网络上读取它,它可以(或多或少)工作,但如果我从本地文件读取它,它就不起作用。

这是从网络上读取它的代码:

 public async void ExamineJson()
    {
        string responseText = await GetjsonStream();
        ParseJson(responseText);
    }


public async Task<string> GetjsonStream()
    {
        HttpClient client = new HttpClient();
        string url = "http://rmarinho.facilit.us/app/d/rtp/config.json";
        HttpResponseMessage response = await client.GetAsync(url);
        return response.Content.ReadAsString();
    }



    private static void ParseJson(string responseText)
    {
        JsonObject root = new JsonObject(responseText);
        string epg = root.GetNamedString("epgurl");

        JsonArray themes = root["themes"].GetArray();

        for (int i = 0; i < themes.Count; i++)
        {

            JsonObject section = themes[i].GetObject();

        }

    }

所以这可行,但是如果我使用相同的解析方法并使用此代码从我的应用程序中的本地文件获取文件,如果失败并出现错误“WinRT信息:WEB_E_INVALID_JSON_STRING”。

FileSync.Read<string>(installedLocation, "config.json",
           (fileSize, reader) =>
               reader.ReadString(fileSize),
               responseText =>
               {
                   ParseJson(responseText);

               })

   public static class FileSync
{
    public static async void Read<TDocument>(StorageFolder folder, string fileName,
        Func<uint, DataReader, TDocument> reader, Action<TDocument> completion = null)
    {


        StorageFile file;
        IRandomAccessStream stream;
        IInputStream inputStream;
        DataReader dr;

        file = await folder.GetFileAsync(fileName);

        stream = await file.OpenAsync(FileAccessMode.Read);
        inputStream = stream.GetInputStreamAt(0);

        uint fileSize = (uint)stream.Size;

        dr = new DataReader(inputStream);
        await dr.LoadAsync(fileSize);

        Task<TDocument> task = new Task<TDocument>(() => reader(fileSize, dr));
        task.Start();
        TDocument doc = await task;

        if (completion != null)
        {
            completion(doc);
        }
    }

    public static async void Write<TDocument>(StorageFolder folder, string fileName,
CreationCollisionOption collisionOption, TDocument doc,
Action<DataWriter, TDocument> writer, Action<bool> complete = null)
    {
        StorageFile creator;
        IRandomAccessStream stream;
        IOutputStream outputStream;
        DataWriter dw;

        creator = await folder.CreateFileAsync(fileName, collisionOption);

        stream = await creator.OpenAsync(FileAccessMode.ReadWrite);
        outputStream = stream.GetOutputStreamAt(0);

        dw = new DataWriter(outputStream);

        Task task = new Task(() => writer(dw, doc));
        task.Start();
        await task;

        await dw.StoreAsync();
        bool success = await outputStream.FlushAsync();
        if (complete != null)
        {
            complete(success);
        }
    }
}

任何人都可以帮我弄清楚这是预览版本中的错误还是我缺少的东西?!

提前致谢

I have tried multiple ways to parse json in Windows 8 and i m getting this error alot.

"WinRT information: WEB_E_INVALID_JSON_STRING"

It gets to a point that i use the same json string, and it works (more or less) if i read from it from the web, but it won't work if i read it from a local file.

heres the code to read it from the web:

 public async void ExamineJson()
    {
        string responseText = await GetjsonStream();
        ParseJson(responseText);
    }


public async Task<string> GetjsonStream()
    {
        HttpClient client = new HttpClient();
        string url = "http://rmarinho.facilit.us/app/d/rtp/config.json";
        HttpResponseMessage response = await client.GetAsync(url);
        return response.Content.ReadAsString();
    }



    private static void ParseJson(string responseText)
    {
        JsonObject root = new JsonObject(responseText);
        string epg = root.GetNamedString("epgurl");

        JsonArray themes = root["themes"].GetArray();

        for (int i = 0; i < themes.Count; i++)
        {

            JsonObject section = themes[i].GetObject();

        }

    }

So this works, but if i use the same parse method and use this code to get file from local file in my app if failswith the error "WinRT information: WEB_E_INVALID_JSON_STRING" .

FileSync.Read<string>(installedLocation, "config.json",
           (fileSize, reader) =>
               reader.ReadString(fileSize),
               responseText =>
               {
                   ParseJson(responseText);

               })

   public static class FileSync
{
    public static async void Read<TDocument>(StorageFolder folder, string fileName,
        Func<uint, DataReader, TDocument> reader, Action<TDocument> completion = null)
    {


        StorageFile file;
        IRandomAccessStream stream;
        IInputStream inputStream;
        DataReader dr;

        file = await folder.GetFileAsync(fileName);

        stream = await file.OpenAsync(FileAccessMode.Read);
        inputStream = stream.GetInputStreamAt(0);

        uint fileSize = (uint)stream.Size;

        dr = new DataReader(inputStream);
        await dr.LoadAsync(fileSize);

        Task<TDocument> task = new Task<TDocument>(() => reader(fileSize, dr));
        task.Start();
        TDocument doc = await task;

        if (completion != null)
        {
            completion(doc);
        }
    }

    public static async void Write<TDocument>(StorageFolder folder, string fileName,
CreationCollisionOption collisionOption, TDocument doc,
Action<DataWriter, TDocument> writer, Action<bool> complete = null)
    {
        StorageFile creator;
        IRandomAccessStream stream;
        IOutputStream outputStream;
        DataWriter dw;

        creator = await folder.CreateFileAsync(fileName, collisionOption);

        stream = await creator.OpenAsync(FileAccessMode.ReadWrite);
        outputStream = stream.GetOutputStreamAt(0);

        dw = new DataWriter(outputStream);

        Task task = new Task(() => writer(dw, doc));
        task.Start();
        await task;

        await dw.StoreAsync();
        bool success = await outputStream.FlushAsync();
        if (complete != null)
        {
            complete(success);
        }
    }
}

Anyone can help me out figure if this a bug from the preview version or is something that i m missing?!

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

↙厌世 2025-01-08 07:24:37

想通了这一点。当我从文件中读取 JSON 时,我用来读取文件的方法是复制 UTF8 ByteOrderMark 字符添加到结果流中。结果,当我调用 stringFromFile.equals(hardcodedString) 时返回 false。我使用以下代码从文件中读取文本并剥离 BOM,现在使用 Windows.Data.Json 解析 JSON 有效。

private readonly static string UTF8_BYTE_ORDER_MARK =
    Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble(), 0, Encoding.UTF8.GetPreamble().Length);


        private string GetStringContentsOfFile(string path)
        {
            Uri filePath = new Uri(path);
            var jsonFileTask = StorageFile.GetFileFromApplicationUriAsync(filePath).AsTask();
            jsonFileTask.Wait();
            var jsonFile = jsonFileTask.Result;

            var getStringContentsTask = FileIO.ReadTextAsync(jsonFile, Windows.Storage.Streams.UnicodeEncoding.Utf8).AsTask();
            getStringContentsTask.Wait();
            var text = getStringContentsTask.Result;

            // FileIO.ReadTextAsync copies the UTF8 byte order mark into the result string. Strip the byte order mark
            text = text.Trim(UTF8_BYTE_ORDER_MARK.ToCharArray());

            return text;

        }

Figured this out. When I read JSON from a file, the method I'm using to read the file is copying the UTF8 ByteOrderMark character to the result stream. As a result, when I call stringFromFile.equals(hardcodedString) returns false. I used the following code to read the text from a file and strip the BOM and now parsing the JSON using Windows.Data.Json works.

private readonly static string UTF8_BYTE_ORDER_MARK =
    Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble(), 0, Encoding.UTF8.GetPreamble().Length);


        private string GetStringContentsOfFile(string path)
        {
            Uri filePath = new Uri(path);
            var jsonFileTask = StorageFile.GetFileFromApplicationUriAsync(filePath).AsTask();
            jsonFileTask.Wait();
            var jsonFile = jsonFileTask.Result;

            var getStringContentsTask = FileIO.ReadTextAsync(jsonFile, Windows.Storage.Streams.UnicodeEncoding.Utf8).AsTask();
            getStringContentsTask.Wait();
            var text = getStringContentsTask.Result;

            // FileIO.ReadTextAsync copies the UTF8 byte order mark into the result string. Strip the byte order mark
            text = text.Trim(UTF8_BYTE_ORDER_MARK.ToCharArray());

            return text;

        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文