2017-08-31 133 views
2

我是新開發的Windows UWP應用程序,我正試圖從我的資產文件夾中解析JSON文件。我看過很多教程,但是當我嘗試過時,他們不工作。請有人幫我解析一下,如果你能舉一個例子。如何從UWP中的Assets文件夾解析JSON文件 - 已關閉

我使用VS2017和C#;

這是我想使用的庫:

using Windows.Data.Json; 

我的代碼是:

private Uri appUri = new Uri("ms-appx:///Assets/marker.json"); 
private string title; 
private void ConverJSONtoObjects() 
     { 
      try 
      { 
       Uri appUri = new Uri(fileName);//File name should be prefixed with 'ms-appx:///Assets/*  
                StorageFile anjFile = StorageFile.GetFileFromApplicationUriAsync(appUri).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();  
                string jsonText = FileIO.ReadTextAsync(anjFile).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();  
       JsonArray obj = JsonValue.Parse(jsonText).GetArray(); 
       for (uint i = 0; i < obj.Count; i++) 
       { 
        title = obj.GetObjectAt(i).GetNamedString("name"); 
       } 
       message("Place", title); 
      } 
      catch (Exception ex) 
      { 
       message("Error", ex.ToString()); 
      } 

     } 

我得到這個錯誤: error handled by Exception

我的文件是這樣的:

[ 
{ 
"id":1, 
"name":"Cabañas Nuevo Amanecer", 
"lat":"18.402785", 
"lng":"-70.094953", 
"type":"Normal", 
"phone":"No Disponible", 
"price":"DOP 500", 
"image":"http://i65.tinypic.com/10mif69.jpg" 
}, 
{ 
"id":2, 
"name":"Cabañas Costa Azul", 
"lat":"18.424746", 
"lng":" -69.990333", 
"type":"Lujosa", 
"phone":"(809) 539-6969", 
"price":"DOP 4453", 
"image":"http://i64.tinypic.com/wcd5b8.png" 
} 
] 
+0

你應該提供更多關於你不明白的細節,因爲如果你只是想解析,就像Windows.Data.Json.JArray.Parse(jsonString)一樣簡單; –

+0

@CyprienAutexier讓我們來看看這是否對你有所幫助 –

+0

那麼這個代碼有什麼問題呢? (除了標題沒有聲明,消息在循環之外,並且總是顯示最後一個值) –

回答

3

您可能正在尋找無數的JSON庫之一。你應該從Json.Net開始,這是最受歡迎的選擇。 (您可以看看Service Stack Text,FastJsonParserJil等替代方案)。

一個簡單的方法是將聲明一個類符合預期的數據模式:

public class PointOfInterest 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    // ... 
} 

而且使用反序列化:

var poiArray = JsonConvert.DeserializeObject<PointOfInterest[]>(jsonString, new JsonSerializerSettings 
    { 
     ContractResolver = new CamelCasePropertyNamesContractResolver() 
    }); 

編輯等等,並提供更新的要求,你必須做像這樣的事情:

var array = JArray.Parse(jsonString); 

foreach(JObject item in array){ 
    var poi = new PointOfInterest() 
    poi.Id = (int)item.GetNamedNumber("id"); 
    //... 
} 

official documentation是相當straig htforward。

+0

謝謝,唯一的問題是我不想使用外部庫的Windows,除非它是我的最後一個選項。我可以使它與HTTPClient請求一起工作,但我希望它可以從我的資產文件夾 –

+1

@MisterJJ中工作,然後您可以使用DataContractSerializer https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer (v = vs.110).aspx,但是:這是垃圾(非常有限的功能支持和緩慢)。例如Miscrosoft AspNet Core團隊已經選擇了Json.Net來支持Json。 –