2012-03-09 62 views
0

如何使用Monodroid的System.Json命名空間將任意隨機對象轉換爲JSON字符串?我看到那裏的類(JsonObject,JsonVlaue等),我可以反序列化就好了。但序列化正在逃避我。如何使用Monodroid的System.Json將對象序列化爲JSON?

+0

我相信System.Json上的當前答案是它只存在於非常輕量級反序列化 - http://stackoverflow.com/questions/5399506/using-system-json-to-convert-c-sharp-arrays-and-objects-to-a-json-string和http://stackoverflow.com/questions/5026985/how-to-serialize-using-system-json-in-monotouch - 所以你最好使用Newtonsoft的Json.Net或ServiceStack的JSON支持端口 – Stuart 2012-03-10 11:33:18

+0

@Stuart:請使這個評論成爲一個答案。我可以接受並關閉它。謝謝。 – 2012-03-24 00:37:13

+0

:)完成!對不起,這不是更好的消息! – Stuart 2012-03-24 12:11:13

回答

0

使用這個示例模型:

class MyModel 
{ 
    public string Name { get; set; } 
} 

可以使用DataContractJsonSerializer類對象序列化到JSON:

var model = new MyModel {Name = "Greg"}; 
var serializer = new DataContractJsonSerializer(typeof (MyModel)); 

using (var stream = new MemoryStream()) 
{ 
    serializer.WriteObject(stream, model); 

    string json = Encoding.Default.GetString(stream.ToArray()); 

    Console.WriteLine(json); 
} 

該代碼會輸出這個JSON:

{"Name":"Greg"} 

如果您沒有綁定到內置的.NET序列化庫,則可能需要檢出Json.NETServiceStack

+0

這實際上適合你嗎?我很好奇,因爲其他示例聲明您必須將MyModel類作爲DataContract和可序列化參數裝飾爲DataMember – 2013-10-31 10:18:13

相關問題