How can I deserialize a JSON string in Mono?

2019-03-24 13:40发布

问题:

How can I deserialize a JSON string in C# (Mono)?

Is there a JSON library and instructions on how to install it? I'm using fedora 14.

回答1:

we are not utilizing json contract serializer - instead we use Json.NET. it should work with mono too.
you don't need to install the assembly, just add a reference and supply it with your final package!

EDIT:
how to add a reference? though i'm not a mono-devlop-er ... taken from here:

References -> Edit References -> .NET Assembly -> Browse to file & select it

otherwise: hey, just hit F1!



回答2:

I recommend looking at ServiceStack.NET Text. It is incredibly fast compared to JSON.NET.

Examples of serializing a dictionary:

ServiceStack.NET

var jsonSerializer = new JsonSerializer<Dictionary<String, Object>>();
var result = jsonSerializer.SerializeToString(dict);

JSON.NET

var result = JsonConvert.SerializeObject(dict, Formatting.Indented);


回答3:

Take a look at JSON.NET:

http://components.xamarin.com/gettingstarted/json.net

Features:

  • Flexible JSON serializer for converting between .NET objects and JSON
  • LINQ to JSON for manually reading and writing JSON
  • High performance, faster than .NET's built-in JSON serializers
  • Write indented, easy to read JSON
  • Convert JSON to and from XML

Example to serialize and deserialize:

    using Newtonsoft.Json;
    ...

    public class Person
    {
        public string Name { get; set; }
        public DateTime Birthday { get; set; }
    }

    void PersonToJsonToPersonExample ()
    {
        var person = new Person { Name = "Bob", Birthday = new DateTime (1987, 2, 2) };

        var json = JsonConvert.SerializeObject (person);
        Console.WriteLine ("JSON representation of person: {0}", json);

        var person2 = JsonConvert.DeserializeObject<Person> (json);
        Console.WriteLine ("{0} - {1}", person2.Name, person2.Birthday);
    }


标签: c# .net json mono