English 中文(简体)
• 如何序列化和淡化Json的不动产。 净额
原标题:How to serialise and deserialise an object property set to an enum value in Json.Net
  • 时间:2011-10-17 23:57:58
  •  标签:
  • json.net

我有一个C#类,有价值物品。 我将这种财产归为一面价值,序列化到Json,然后将它重新注入物体。

How can I make the object s property value deserialise back to the enum?

这是因为:

public class Foo
{
   public object Value { get; set; }
}
public enum SmallNumbers { One, Two, Three }

我怎样才能使这一检验顺从?

   [Test]
   public void an_object_property_set_to_an_enum_can_be_serialised()
   {
      var settings = new JsonSerializerSettings
                        {
                           TypeNameHandling = TypeNameHandling.Auto
                        };

      var json = JsonConvert.SerializeObject(
         new Foo {Value = SmallNumbers.One},
         Formatting.None,
         settings);

      var foo = JsonConvert.DeserializeObject<Foo>(json, settings);

      Assert.That(foo.Value is SmallNumbers);
   }
最佳回答

可能为这一特殊案件写一个变换人,但如果你拥有像类型价值这样的许多财产,我就没有好处。 反对意见,因为没有任何东西可以告诉哪类人去改变每个目标。 核对以下代码;对你的机器进行测试。

using System;
using Newtonsoft.Json;
using NUnit.Framework;

class StackOverflowIssue7801000
{
    public enum SmallNumbers { One, Two, Three }

    public class Foo
    {
        public object Value { get; set; }
    }

    class ObjectToSmallNumbersConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            // Not required for deserialization
            throw new NotImplementedException();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return (SmallNumbers)Convert.ToInt32(reader.Value);
        }

        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(object));
        }
    }

    [Test]
    public void an_object_property_set_to_an_enum_can_be_serialised()
    {
        var settings = new JsonSerializerSettings {
            TypeNameHandling = TypeNameHandling.All
        };

        var json = JsonConvert.SerializeObject(new Foo { Value = SmallNumbers.Three }, Formatting.None, settings);
        settings.Converters.Add(new ObjectToSmallNumbersConverter());
        var foo = JsonConvert.DeserializeObject<Foo>(json, settings);
        Assert.That(foo.Value is SmallNumbers);
    }
}
问题回答

暂无回答




相关问题
Parsing JSON with JSON.NET

I have a JSON string: {"responseData": {"results": [ {"GsearchResultClass": "GblogSearch", "title":"u003cbu003eParis Hiltonu003c/bu003e shops at Sydney Michelle ...

Parse and filter javascript array

Our legacy code uses Newtonsoft.Json.JsonWriter to produce a javascript array like: [["1","zxc"],["2","fifa"],["3","fgh"]]. I wonder if Newtonsoft.Json provides counterparts to help filter out or ...

JSON.NET to C# objects

Im trying to use JSON.NET framework in a windows Form to read some information from a JSON string. But im struggling to get the Dictionaries from the taxonomies->topics array and the clusters { ...

Json.NET, Unable to de-serialize nullable type

I m trying to convert JSON to C# object using Json.NET. The object looks like this in C#: public class MyObject { public int? integerValue {get;set;} public DateTime? dateTimeValue {get;set;} ...

DI and JSON.NET

I m using JSON.NET to serialize and deserialize object for different purposes. I m a big fan of DI but the code below gives me the chills. Is smells like bad code: public class Foo : Baz { ...

mvc return Json() vs. JSON based Web Service

I want to expose a service on my site that any users can call and get a JSON response. In the end, I want the users to be using this service as much as possible. My site is created using the asp.net ...

热门标签