[英]Parse dictionary from json windows phone
我有兩段代碼
代碼1
string json = @"{""properties"":{""name"":""carl""}}";
try
{
MemoryStream stream = GetMemoryStreamFromString(json);
Type type = typeof(Person);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
object obj = serializer.ReadObject(stream);
Debug.WriteLine(obj);
Person person = obj as Person;
}
catch (Exception ee)
{
Debug.WriteLine(ee.Message);
}
//And my classes
[DataContract]
public class Person
{
[DataMember]
public Property properties { set; get; }
public Person() { }
}
[DataContract]
public class Property
{
[DataMember]
public string name { set; get; }
public Property() { }
}
碼2
string json = @"{""properties"":{""name"":""carl""}}";
try
{
MemoryStream stream = GetMemoryStreamFromString(json);
Type type = typeof(Person);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
object obj = serializer.ReadObject(stream);
Debug.WriteLine(obj);
Person person = obj as Person;
}
catch (Exception ee)
{
Debug.WriteLine(ee.Message);
}
//And my class
[DataContract]
public class Person
{
[DataMember]
public Dictionary<string,string> properties { set; get; }
public Person() { }
}
Code1工作正常,但Code2給我例外。 這是日志
數據協定類型'ScrollViewExample.Person'無法反序列化,因為成員'properties'不是公共的。 公開該成員將解決此錯誤。 或者,可以將其設置為內部,並在程序集中使用InternalsVisibleToAttribute屬性以啟用內部成員的序列化-有關更多詳細信息,請參見文檔。 請注意,這樣做有一定的安全隱患。
這里的問題是我沒有為properties
定義一個結構,它可以具有任何鍵,因此無法為其定義類。 我發布此問題是因為我有問題 ,經過調查后發現我無法解析字典。 所以我將我的問題簡化為一個簡單的問題,以便你們可以提供您的意見
不幸的是DataContractJsonSerializer
希望您的json數據為
{"properties":[{"Key":"Name","Value":"Valorie"},{"Key":"Month","Value":"May"},{"Key":"Year","Value":"2013"}]}
我認為使用Json.NET是解析json的一個好主意
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.