我正在從API接收JSON字符串,這種字符串的結構不是在應用程序中處理的好方法。C#自定義對象的序列化列表
我選擇爲這個JSON數據創建一個自定義串行器(而不是在應用程序中接收和使用的數據有兩個不同的類)。
以下很多教程,我設法將單個對象的自定義串行器放在一起。但是,我需要處理這些對象的列表(這些怪異列表中會有更多不同的數據,需要自定義處理)。
有沒有內置的方法,我可以設置我的自定義serialiser與列表中的每個對象一起工作?還是我需要手動拆分JSON對象,並將它的大塊餵給自定義的序列化程序?
任何其他建議如何處理這種情況表示讚賞。
用戶類:
[JsonConverter(typeof(UserSerializer))]
public class User
{
public int id;
public string displayName;
public string email;
public int total_points;
public float total_values;
}
的解串器:
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
JObject jObjectRoot = JObject.Load(reader);
var root = jObjectRoot.Properties().ToList();
JObject jObjectData = JObject.Load(root[2].Value.CreateReader());
var data = jObjectData.Properties().ToList();
return new User {
id = (int)root[1].Value,
displayName = (string)data[0].Value,
email = (string)data[1].Value,
total_points = (int)data[2].Value,
total_values = (float)data[3].Value
};
}
UPDATE:
也是解析JSON字符串到單個用戶對象的代碼:
public static void ProcessJSON(string json)
{
User user = JsonConvert.DeserializeObject<User>(json);
}
和JS本身:
[
{
"type": "users",
"id": 1,
"attr": {
"display_name": "user2",
"email": "[email protected]",
"total_points": 4,
"total_values": 32.34
},
"relationships": {
"points_received": {
"links": {
"self": "tipjar/users/1/relationships/points",
"related": "tipjar/users/1/points"
}
},
"points_given": {
"links": {
"self": "tipjar/users/1/relationships/awarded",
"related": "tipjar/users/1/awarded"
}
}
}
}
]
感謝
你看着使用Newtonsoft JSON.NET? –
JSON的外觀如何? –
@GlenThomas是的,我正在使用Newtonsoft JSON.NET – Kiaurutis