因此,我在網上隨處看到了幾個關於如何解析JSON字符串並將該信息保存到特定變量的示例,但我對C#和Windows Phone 7開發極其新穎(僅限於一直這樣做了一個星期,但我很快就採用它,因爲我很瞭解C++)。我很難理解我應該如何處理這個問題,所以我只會給你我想解析的代碼和我到目前爲止的代碼。在Windows Phone 7中的JSON解析
我已經使用http://jsonlint.com/驗證器驗證了我的JSON信息。下面是我想解析JSON信息(位於網站上):
[
{
"id": 19019,
"model": "tester",
"fields":
{
"name": "thename",
"slot": 45,
"category": "thecategory"
}
}
]
這裏是我試圖用它來解析JSON信息,並將其存儲爲變量,這樣我可以調用的代碼後來在節目信息:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Resources;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace PhoneApp
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}
private void myButton_Click(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
client.OpenReadCompleted += (s, eargs) =>
{
var serializer = new DataContractJsonSerializer(typeof(RootObject));
var theItem = (RootObject)serializer.ReadObject(eargs.Result);
myTextBlock.Text = theItem.pk.ToString();
};
client.OpenReadAsync(new Uri("http://www.example.com/i/19019/json"));
}
}
public class RootObject
{
public int pk { get; set; }
public string model { get; set; }
public Item item { get; set; }
}
public class Item
{
public string name { get; set; }
public int slot { get; set; }
public string category { get; set; }
}
}
至於這段代碼而言,myTextBlock在我的Windows Phone 7應用程序中的文本塊具有顯示文本的空間和myButton爲按鈕的用戶點擊以顯示文本(一旦我修正了這個問題,我將以不同的方式顯示文本)。現在,只要我啓動這個代碼,它就會初始化應用程序,但是當我點擊按鈕時,它給了我一個InvalidCastException未處理與具體當從一個數字投射時,該值必須是一個數字少一些比無限。錯誤,代碼:
var theItem = (RootObject)serializer.ReadObject(eargs.Result);
我希望我已經給了足夠的信息來幫助我解決這個問題。我寧願使用默認情況下內置於Windows Phone 7 SDK中的庫,但如果我正在嘗試使用JSON.NET或其他兼容的外部庫進行處理,那麼我會願意學習如果你提供適當的鏈接來學習它。我感謝你們可以給予的幫助。
乾杯!
這將是有益的,除了我甚至無法將JSON字符串放入這些變量中。我不知道什麼是錯的。 :/ – th3n3wguy 2011-12-27 18:29:18
是關於JSON序列化或如何獲取JSON字符串的問題嗎?或者是其他東西? – 2011-12-27 20:23:25
我會老實說,我不太明白什麼時候需要序列化以及何時反序列化。我想要做的就是獲取JSON文件中每個字段的值,並將該信息保存到一個變量中,以便我可以用自己的方式顯示它,而不是僅以字符串形式顯示。這有幫助嗎? – th3n3wguy 2011-12-28 20:25:11