How to serialize using System.Json in MonoTouch

2019-02-26 11:05发布

问题:

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