JSON de-serialization with MonoTouch

后端 未结 2 654
一个人的身影
一个人的身影 2021-01-05 09:17

there are various ressources on the web explaining how to serialize some C# object to a JSON string. I have been unable to get any of them to work with MonoTouch 3.2

2条回答
  •  青春惊慌失措
    2021-01-05 09:55

    I'd recommend using the System.Json library, which is not too difficult to use and wrap in a class to make it strongly typed. It is also included as a default assembly with MonoTouch as it was inherited from Silverlight.

    To load it up:

    JsonValue value = JsonObject.Load(stream); //There are other overloads here, my stream is off an HttpWebRequest
    

    Here is an example by index:

    this.StringValue = value[0];
    this.IntValue = value[1];
    

    One my name:

    this.StringValue = value["StringValue"];
    this.IntValue = value["IntValue"];
    

    Where this is a class with a string property named StringValue and an int property named IntValue. For the most part, the JsonValue class will cast to your types implicitly.

    So what I do, is create a class to hold all of the Json info in a strongly typed way, then pass in a JsonValue in the constructor to do the ugly weakly typed stuff.

    For other libraries, you will run into problems where MonoTouch strips out types that are seen to be "unused" when created by reflection (as when you use XmlSerializer, for example). I have found myself fighting that issue more than necessary, having to add PreserveAttribute on types, etc.

    On this issue, read here for more info on Preserve: MonoTouch Doc

提交回复
热议问题