现在我有这个JSON:
[
"bekasi",
"bekasi barat",
"bekasi selatan",
"bekasi timur",
"bekasi utara",
"serang bekasi"
]
我不知道如何制作解析器类。我尝试了在线 json 到 c# 类生成器,但它无济于事。所以我试了这个:
[DataContract]
public class kota
{
[DataMember]
public string kotanya { get; set; }
}
而这个
public static kota eks; // I also tried public static kota[] eks;
public void mulai()
{
string eksp = "http://www.ongkoskirim.com/api/0.2/?id=OAL66afd139a386fee6dc5a5597abd7daba&q=city&s=bek";
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(eksp), UriKind.Absolute);
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
var ser = new DataContractJsonSerializer(typeof(kota)); //and I have tried typeof(IEnumerable<kota>)
System.Diagnostics.Debug.WriteLine("sini");
eks = (kota)ser.ReadObject(e.Result); //I also tried (kota[])ser.ReadObject(e.Result);
System.Diagnostics.Debug.WriteLine("sana");
List<string> temp = new List<string>();
temp.Add("Semua");
System.Diagnostics.Debug.WriteLine("list");
for (int i = 0; i < 3; i++)
{
System.Diagnostics.Debug.WriteLine(eks.kotanya[i]);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
}
但我总是得到无效的CastException。谁能帮我?
你不需要任何额外的类,因为你的JSON是简单的字符串数组:
var ser = new DataContractJsonSerializer(typeof(string[]));
var items = (string[]) ser.ReadObject(e.Result);
在您的 JSON 变得更加复杂之前,我不会涉及专用类,但您可以轻松构建kota
实例列表:
var kotas = items.Select(i => new kota { kotanya = i }).ToList();
附带说明一下,如果您打算进行更多的 JSON 反序列化,我建议您查看 JSON.NET 库。
由于它是一个要序列化的数组,您应该尝试此操作
var ser = new DataContractJsonSerializer(typeof(kota[]));
如果需要使用类,则必须通过将 kotanya
属性更改为字符串集合和 JSON 字符串来修改kota
类(添加数据成员的名称kotanya
以描述字符串集合并用 {}
括起来的字符串),然后再进行处理:
static void Main(string[] args)
{
string json = "{"kotanya":["bekasi","bekasi barat","bekasi selatan","bekasi timur","bekasi utara","serang bekasi"]}";
var s = new DataContractJsonSerializer(typeof(kota));
using (var m = new MemoryStream(Encoding.ASCII.GetBytes(json)))
{
var r = s.ReadObject(m);
}
}
[DataContract]
public class kota
{
[DataMember]
public string[] kotanya { get; set; }
}