如何在 MonoTouch 中使用 System.Json 进行序列化 [英] How to serialize using System.Json in MonoTouch
问题描述
我的其他问题似乎太笼统了,所以我想我会创建一个新的细节.抱歉,如果这被认为是不好的做法.
My other question seems to be too generic, so I tought I'd create a new one on the details. Sorry if that is considered bad practice.
我正在尝试使用 MonoTouch 和 System.Json 命名空间将 C# 对象序列化为 JSON 字符串,这种方式不需要我自己遍历对象.那可能吗?如果是,如何正确操作?
I am trying to serialize C# objects to JSON strings with MonoTouch and the System.Json namespace in a way that doesn't require me to descend through the object(s) myself. Is that possible? If yes, how to do it properly?
反序列化通过将 JsonValue 隐式转换为字符串、int 等来很好地工作.此外,在层次结构中降序也没有问题.像这样:
De-serialization works well by implicitly casting a JsonValue to a string, int, whatever. Also, descending in the hierarchy is no problem. Like so:
JsonValue json = JsonValue.Parse(jsonString);
int mainValue = json["mainValue"];
JsonValue subValues = json["subValues"];
int subValue1 = subValues["subValue1"];
相反的情况只适用于元素类型(string/int/...).不幸的是,其他对象无法转换为 JsonValue/JsonObject.甚至不是只有两个整数的简单结构.
The opposite is only possible with elemental types (string/int/...). Other objects cannot be cast to JsonValue/JsonObject unfortunately. Not even really simple structs with just two ints.
// This works
JsonValue json = new JsonObject(new KeyValuePair<string,JsonValue>("mainValue", 12345));
// Cannot (implicitly) convert type 'MyObjectType' to 'System.Json.JsonValue'
MyObjectType myObject = new MyObjectType();
JsonValue subValues = myObject;
// Cannot (implicitly) convert type 'MySimpleStruct' to 'System.Json.JsonObject'
MySimpleStruct myStruct;
myStruct.x = 1;
myStruct.y = 2;
JsonValue myStructJson = myStruct;
由于我的对象嵌套了多个级别的其他对象,因此我自己遍历它并分配所有值将是一个很棒的 PITA.System.Json 有没有更简单的方法?
As my object has several levels of other objects nested within, walking through it by myself and assigning all the values would be a great PITA. Is there a simpler way with System.Json?
推荐答案
System.Json 不支持这样的任意序列化.
System.Json doesn't support arbitrary serialization like this.
你可以使用像 Newtonsoft 这样的第三方 Json 库,或者等待 MonoTouch v4,它会有 DataContractJsonSerializer
You can use a third party Json library like Newtonsoft, or wait for MonoTouch v4 which will have the DataContractJsonSerializer
这篇关于如何在 MonoTouch 中使用 System.Json 进行序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!