Using System.Json for non-Silverlight projects?

前端 未结 5 1867
鱼传尺愫
鱼传尺愫 2020-12-31 10:18

Any idea on how to do it? If not possible, what\'s a good JSON library for C#?

相关标签:
5条回答
  • 2020-12-31 11:07

    System.Json is now available in non-Silverlight projects via NuGet (.Net's package management system) and is hopefully going to be released as part of the core framework in vnext. The NuGet package is named JsonValue.

    Imagine that we have the following JSON in the string variable json:

    [{"a":"foo","b":"bar"},{"a":"another foo","b":"another bar"}]
    

    We can get write the value "another bar" to the console using the following code:

    using System.Json;
    dynamic jsonObj = JsonValue.Parse(json);
    var node = jsonObj[1].b;
    System.Console.WriteLine(node.Value);
    
    0 讨论(0)
  • 2020-12-31 11:09

    If you're just looking for JSON encoding/decoding, there is an official System.Web extension library from Microsoft that does it, odds are you probably already have this assembly (System.Web.Extensions):

    http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

    Example:

    using System;
    using System.Web.Script.Serialization;
    
    class App 
    {
        static void Main(string[] args = null)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            String sJson = "{\"Name\": \"Your name\"}";
            DesJson json = jss.Deserialize<DesJson>(sJson);
    
            Console.WriteLine(json.Name);
        }
    }
    
    class DesJson {
        public string Name {get; set;}
    }
    
    0 讨论(0)
  • 2020-12-31 11:15

    Here's an extenstion method to serialize any object instance to JSON:

    public static class GenericExtensions
    {
        public static string ToJsonString<T>(this T input)
        {
            string json;
            DataContractJsonSerializer ser = new DataContractJsonSerializer(input.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                ser.WriteObject(ms, input);
                json = Encoding.Default.GetString(ms.ToArray());
            }
            return json;
        }
    }
    

    You'll need to add a reference to System.ServiceModel.Web to use the DataContractSerializer.

    0 讨论(0)
  • 2020-12-31 11:17

    Another option is to use Mono's implementation of System.Json, I was able to backport it to C# 2.0 with a few minor changes.

    You can simply download my C# 2.0 project from here.

    0 讨论(0)
  • 2020-12-31 11:24

    Scott Guthrie blogged about this

    http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx

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