简体   繁体   中英

C# How to save part of nested JSON into object property, but not deserialized?

This is my JSON

{
    "type": "user_settings",
    "created_at": 1610973280043,
    "data": {
        "user_id": 12345,
        "updated_at": "2021-01-18T15:34:40+03:00"
    }
}

These are my classes:

public class BaseMessage
{
    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("created_at")]
    public long CreatedAt { get; set; }

    [JsonProperty("data")]
    public DataDTO Data { get; set; }

    public string DataJson {get; set;} // <-- Here I need string like this "{ "user_id": 12345, "updated_at": "2021-01-18T15:34:40+03:00" }"
}

public class DataDTO
{
    [JsonProperty("user_id")]
    public int UserId { get; set; }

    [JsonProperty("updated_at")]
    public DateTime? UpdatedAt { get; set; }
}

So I need parsed "data" (it works ok) and save nested JSON as a string (I don't know how). Is there elegant way to save nested JSON into string property?

Something like this:

public class BaseMessage
{
    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("created_at")]
    public long CreatedAt { get; set; }

    [JsonProperty("data")]
    public DataDTO Data { get; set; }

    [JsonPropertyAsString("data")] // <-- This is my fantasy :)
    public string DataJson {get; set; }
}

As @dbc commented you can create a custom JsonConverter for the DataJson property, but you also should do something with your another property which is mapped from the data JSON field - Data of DataDTO type. I can propose the following solution:

1. Custom JSON Converter (I took this from @dbc's answer )

public class RawConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
       if (reader.TokenType == JsonToken.Null)
          return null;
       var raw = JRaw.Create(reader);
       return raw.ToString();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
       var s = (string)value;
       writer.WriteRawValue(s);
     }
}

2. Decorate your DataJson property with the JsonConverter attribute and remove JsonPropertyAttribute for the Data property

Note that if you don't remove the JsonPropertyAttribute then it won't work, since you have two properties which are mapped from the same JSON field, and as I know this is not supported by Json.NET by default.

public class BaseMessage
{
   [JsonProperty("type")]
   public string Type { get; set; }

   [JsonProperty("created_at")]
   public long CreatedAt { get; set; }

   public DataDTO Data { get; set; }

   [JsonProperty("data")]
   [JsonConverter(typeof(RawConverter))]
   public string DataJson {get; set;}
}

3. Update your BaseMessage class so this calculates the value of the Data property from DataJson

public class BaseMessage
{
   private DataDTO data;

   [JsonProperty("type")]
   public string Type { get; set; }

   [JsonProperty("created_at")]
   public long CreatedAt { get; set; }

   public DataDTO Data
   {
       if (data == null)
       {
          data = JsonConvert.DeserializeObject<DataDTO>(DataJson);
       }
       return data;
   }

   [JsonProperty("data")]
   [JsonConverter(typeof(RawConverter))]
   public string DataJson {get; set;}
}

Note that I believe this is not the best solution and sure that there are other much better alternatives, but it might be feasible in your case.

Do you mean to use this??

var data = Newtonsoft.Json.JsonConvert.SerializeObject(object);

if yes, install the newtonSoft packge.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM