0
我代表下列對象類型JSON字符串對象以及其他特性:json.net反序列化具有字典屬性,
public partial class Address
{
public Address()
public string Country { get; set; }
public string StreetNo { get; set; }
public string City { get; set; }
public string Zip { get; set; }
public string Complement { get; set; }
public Nullable<int> Latitude { get; set; }
public Nullable<int> Longitude { get; set; }
public Nullable<int> Altitude { get; set; }
public string Url { get; set; }
public System.DateTime LastModified { get; set; }
public byte[] Version { get; set; }
public string StateCode { get; set; }
public string Street { get; set; }
public string RecordStatus { get; set; }
public int UserId { get; set; }
public int AddressId { get; set; }
public Dictionary<string, object> OriginalValues { get; set; }
}
我想創建一個JsonConverter反序列化JSON字符串來上述對象。我被困在什麼添加到我的轉換器來創建我的代碼中的字典。該轉換器的代碼到目前爲止是這樣的:
public class AddressConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
var temp = objectType == typeof(Address);
return temp;
}
public override object ReadJson(JsonReader reader, Type objectType
, object existingValue, JsonSerializer serializer)
{
var obj = JObject.Load(reader);
var model = new Address();
model.Country = Convert.ToString(((JValue)obj["Country"]).Value);
model.StreetNo = Convert.ToString(((JValue)obj["StreetNo"]).Value);
model.City = Convert.ToString(((JValue)obj["City"]).Value);
model.Zip = Convert.ToString(((JValue)obj["Zip"]).Value);
model.Complement = Convert.ToString(((JValue)obj["Complement"]).Value);
model.Latitude = Convert.ToInt32(((JValue)obj["Latitude"]).Value);
model.Longitude = Convert.ToInt32(((JValue)obj["Longitude"]).Value);
model.Altitude = Convert.ToInt32(((JValue)obj["Altitude"]).Value);
model.Url = Convert.ToString(((JValue)obj["Url"]).Value);
model.LastModified = Convert.ToDateTime(((JValue)obj["LastModified"]).Value);
model.StateCode = Convert.ToString((((JValue)obj["Country"]).Value));
model.Street = Convert.ToString(((JValue)obj["StateCode"]).Value);
model.RecordStatus = Convert.ToString(((JValue)obj["RecordStatus"]).Value);
model.UserId = Convert.ToInt32(((JValue)obj["UserId"]).Value);
model.AddressId = Convert.ToInt32(((JValue)obj["AddressId"]).Value);
var encodedString = ((JValue) obj["Version"]).Value.ToString();
model.Version = Convert.FromBase64String(encodedString);
//這裏補充解釋代碼
return model;
}
public override bool CanWrite
{
get
{
return false;
}
}
public override void WriteJson(JsonWriter writer, object value
, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
throw new NotImplementedException();
}
}
我有一個類型,其中包含幾個屬性,包括字典<字符串,對象>存儲原始值和字節[]的版本。當我使用標準JsonConvert.DeserializeObject進行反序列化時,字典和字節數組無法正確實現。自定義轉換器將解決這些問題。如果有一種更簡單的方法來處理這個問題,我很樂意嘗試。謝謝你的幫助。 – 2013-04-24 19:28:43