给定A级...

public class A {
  public string Prop1 { get; set; }
  public string Prop2 { get; set; }
}

string jsonString = JsonConvert.SerializeObject(
     new A() {
        Prop1 = "ABC",
        Prop2 = "$.jqplot.DateAxisRenderer" }
 );


jsonString包含...
“ {
  \“ Prop1 \”:\“ ABC \”,
  \“ Prop2 \”:\“ $。jqplot.DateAxisRenderer \”
}“;

题:

如何取消对Prop2的报价?

即我希望jsonString包含...
“ {
  \“ Prop1 \”:\“ ABC \”,
  \“ Prop2 \”:$。jqplot.DateAxisRenderer
}“;

因此(客户端上)将Prop2评估为参考,而不是字符串

最佳答案

如果要从Prop2中删除引号,则可以为该类型编写JSON.NET JsonConverter并将属性值输出为“原始”。

但是(这很重要),您的输出将不再是有效的JSON。

如果您对这种混合解决方案感到满意,那么一些示例代码如下(假设您已经在项目中引用了JSON.NET):

namespace JsonRawTest
{
    public class AConverter : JsonConverter
    {
        public override bool CanRead { get { return false; } }
        public override bool CanWrite { get { return true; } }

        public override object ReadJson(JsonReader reader, Type objectType,
            object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value,
            JsonSerializer serializer)
        {
            A obj = value as A;
            writer.WriteStartObject();
            writer.WritePropertyName("Prop1");
            writer.WriteValue(obj.Prop1);
            writer.WritePropertyName("Prop2");
            writer.WriteRawValue(obj.Prop2);
            writer.WriteEndObject();
        }

        public override bool CanConvert(Type objectType)
        {
            return typeof(A).IsAssignableFrom(objectType);
        }
    }

    public class A
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var a = new A
            {
                Prop1 = "Some first value",
                Prop2 = "$.jqplot.DateAxisRenderer"
            };

            string json = JsonConvert.SerializeObject(a,
                new JsonConverter[] { new AConverter() });

            ...

        }
    }
}

关于javascript - JSON序列化-如何取消引用属性值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27312700/

10-11 00:17