How to serialize using System.Json in MonoTouch

北慕城南 提交于 2020-01-21 18:02:43

问题


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.

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?

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"];

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;

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?


回答1:


System.Json doesn't support arbitrary serialization like this.

You can use a third party Json library like Newtonsoft, or wait for MonoTouch v4 which will have the DataContractJsonSerializer



来源:https://stackoverflow.com/questions/5026985/how-to-serialize-using-system-json-in-monotouch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!