很可能我沒有經歷過足夠的東西,我的問題有點愚蠢: 爲了學習的目的,我試圖連接到一個REST服務,它提供了JSON數據。帶有動態根對象的JSON
從我所瞭解的情況來看,JSON的目的是將相同的數據傳遞給任何可能的客戶端,而無需擁有自己的狀態。
我的代碼看起來像這樣:
public static void DoSomething()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("SomeUrl"));
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// List data response.
HttpResponseMessage response = client.GetAsync("").Result;
if (response.IsSuccessStatusCode)
{
Task<Stream> readTask = response.Content.ReadAsStreamAsync();
readTask.ContinueWith(task =>
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));
using (Stream result = task.Result)
{
result.Position = 0;
RootObject obj = (RootObject)ser.ReadObject(result);
}
});
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
}
public class Sum
{
public int id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int summonerLevel { get; set; }
public long revisionDate { get; set; }
}
public class RootObject
{
public Sum khalgor { get; set; }
}
但這裏是我的問題:我創建了這個類的「點心」和「RootObject」通過使用本網站http://json2csharp.com/時,JSON字符串是這樣看:
{"khalgor":{"id":23801741,"name":"Khalgor","profileIconId":7,"summonerLevel":30,"revisionDate":1396876104000}}
問題:名稱「Khalgor」似乎被用作根對象,但它是一個名稱。所以如果我想用另一個名字,我不得不使用另一個RootObject。
創建這樣的結構沒有多大意義,所以我的問題是:這裏最好的做法是什麼?我是否將此RootObject/Property手動映射到另一個對象?我是否使用一些反射來動態創建一個屬性或重命名它?
像往常一樣,非常感謝所有響應
馬蒂亞斯
編輯:
我修修補補角落找尋了一下,這是我的一個解決方案的第一個想法:
public static class LOLObjectFactory
{
public static ILOLObject Create(string jsonString)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
Dictionary<String, object> entry = (jss.Deserialize<dynamic>(jsonString) as Dictionary<string, object>).First().Value as Dictionary<String, object>;
Type selectedType = null;
List<string> fieldNames = entry.Select(f => f.Key).OrderBy(f => f).ToList();
Type[] types = typeof(ILOLObject).Assembly.GetTypes();
foreach(var type in types)
{
List<string> typeProperties = type.GetProperties().Select(f => f.Name).OrderBy(f => f).ToList();
if (fieldNames.SequenceEqual(typeProperties) && typeof(ILOLObject).IsAssignableFrom(type))
{
selectedType = type;
break;
}
}
ILOLObject result = System.Activator.CreateInstance(selectedType) as ILOLObject;
foreach(var prop in result.GetType().GetProperties())
{
prop.SetValue(result, entry.First(f => f.Key == prop.Name).Value);
}
return result;
}
}
所以我擁有的所有對象都實現了ILOLObject。我確定它不適用於任何事情,但我想這會是一個好方法?編輯2:只要看看它,我就會看到很多工作要做,但我認爲它背後的想法很清楚。
Json的目的是爲了傳輸目的將數據包裝到字符串表示中。您提到的無狀態適用於REST。 – BlueM