JSON.NET: Serialize json string property into json object

后端 未结 3 1871
北海茫月
北海茫月 2020-12-15 19:10

Is it possible to tell JSON.NET I have a string with JSON data? E.g. I have a class like this:

public class Foo
{
    public int Id;
    public string RawDat         


        
相关标签:
3条回答
  • 2020-12-15 19:23

    You need a converter to do that, here is an example:

    public class RawJsonConverter : JsonConverter
    {
       public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
       {
           writer.WriteRawValue(value.ToString());
       }
    
       public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
       {
           throw new NotImplementedException();
       }
    
       public override bool CanConvert(Type objectType)
       {
           return typeof(string).IsAssignableFrom(objectType);
       }
    
       public override bool CanRead
       {
           get { return false; }
       }   
    }
    

    Then decorate your class with it:

    public class Foo
    {
        public int Id;
        [JsonConverter(typeof(RawJsonConverter))]
        public string RawData;
    }
    

    Then, when you use:

    var json = JsonConvert.SerializeObject(foo,
                                        new JsonSerializerSettings());
    Console.WriteLine (json);
    

    This is your output:

    {"Id":5,"RawData":{"bar":42}}
    

    Hope it helps

    Edit: I have updated my answer for a more efficient solution, the previous one forced you to serialize to then deserialize, this doesn't.

    0 讨论(0)
  • 2020-12-15 19:27

    You can use another property to deserialize the object property json.

    public class Foo
    {
        public int Id;
        public string RawData;
        private object thisObject;
        public object ThisObject 
        {
            get
            {
                return thisObject ?? (thisObject = JsonConvert.DeserializeObject<object>(RawData));
            }
        }        
    }
    
    0 讨论(0)
  • 2020-12-15 19:34

    It is possible, that using JRaw could be more sutable and comapct solution

    see this post

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