JSON de-serialization with MonoTouch

后端 未结 2 632
一个人的身影
一个人的身影 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:47

    I don't have street cred, so I can't post a comment to the answer above..

    Just wanted to post a warning when using the System.Json.JsonObject.ToString() method. I was using this, and it seemed to generate JSON fine.. then I had a string with a return (\n) in it. It didn't escape this properly, and it ended up generating bad JSON..

    So, if you have simple JSON, it may work just fine, but if you know you may have special characters in your strings that require escaping, you should test that "ToString()" method first.

    I think the newtonsoft JSON library looks like an alternative. There is info about this over at Xamarin's site:

    https://components.xamarin.com/view/json.net

    Realize this is an awful answer, but just wanted to post the warning to users of the system json lib.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题