2012-01-31 20 views
7

He intentado varias formas de analizar json en Windows 8 y estoy recibiendo este error mucho.Análisis Json Windows8

"WinRT información: WEB_E_INVALID_JSON_STRING"

Se llega a un punto que yo uso la misma cadena JSON, y funciona (más o menos) si he leído de ella desde la web, pero no va a trabajar si lo leo desde un archivo local.

aquí está el código para leer desde la 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(); 

     } 

    } 

Así que esto funciona, pero si yo uso el mismo método de análisis y utilizando un código para conseguir el archivo del archivo local en mi aplicación si failswith el error "Información de 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); 
     } 
    } 
} 

Cualquiera me puede ayudar a averiguar si esto es un error de la versión de vista previa o es algo que me falta?

Gracias de antemano

+0

¿Una simple prueba de unidad no funciona? – leppie

+0

¿Estás absolutamente seguro de que es la misma cadena? ¿Qué codificación está usando su archivo? –

+0

sí es la misma cadena .. he comparado visualy y en código como cadena xFromserver == cadena yFromlocal es verdadero ... me preguntaba si podría ser algo con el tipo de archivo contente cuando leo el archivo de una fuente local .. parece que no soy el único con problemas: http://phil-it.org/chris/?p=769 –

Respuesta

1

Entendemos esto. Cuando leo JSON desde un archivo, el método que estoy usando para leer el archivo es copiar el carácter UTF8 ByteOrderMark en la secuencia de resultados. Como resultado, cuando llamo a stringFromFile.equals (hardcodedString) devuelve falso. Usé el siguiente código para leer el texto de un archivo y quitar la lista de materiales y ahora el análisis del JSON con Windows.Data.Json funciona.

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; 

     }