簡體   English   中英

調用JsonConvert.SerializeObject時如何轉換編碼的JSON字符串屬性?

[英]How do you convert encoded JSON string properties when calling JsonConvert.SerializeObject?

我有一個帶有一些字符串屬性的POCO,其中包含編碼的JSON對象。

當我調用JsonConvert.SerializeObject時,我想將這些字符串轉換回JSON,並讓Json.NET將它們序列化為嵌入式JSON對象。

調用JsonConvert.SerializeObject時如何轉換編碼的JSON字符串屬性?

以下是相關代碼:

public class LogAction
{
    // other properties
    public string Request { get; set; }
    public string Response { get; set; }
}

這是設置Response屬性的代碼行:

Response = actionExecutedContext.Response?.Content?.ReadAsStringAsync().Result

我包含以下代碼行,以演示使用方法ReadAsStringAsync設置屬性,該方法返回編碼的JSON字符串。 就我而言,它將始終是編碼的JSON字符串或為null。

想法?

您可以通過將轉換器屬性放在JSON屬性上方來使用特定於屬性的轉換器:

public class LogAction
{
  // other properties
  [JsonConverter(typeof(RawJsonConverter))]
  public string Request { get; set; }
  [JsonConverter(typeof(RawJsonConverter))]
  public string Response { get; set; }
}

轉換器將如下,並假設它們已經是JSON來編寫字符串。

public class RawJsonConverter: JsonConverter
{
  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  {
    return JObject.Load(reader).ToString();
  }

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

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

@ckuri使我走上了正確的道路,因此我將他的回答標記為答案,但最終我決定采用其他實現。

這就是我更改實現的原因:

  • 編碼的字符串可以是一個對象,也可以是一個數組。
  • 如果無法解析編碼的字符串屬性,我想要一個明確的錯誤消息。
  • 我在使用JToken.Load(reader)調用時看到一些緩沖區溢出問題。

我希望這會幫助其他人。

    /// <summary>
    /// The RawJsonConverter is used to convert an object's string-typed properties containing valid string-encoded
    /// JavaScript Object Notation (JSON) into non-encoded strings so that they may be treated as JSON objects and
    /// arrays instead of strings when their containing objects are serialized.
    /// Note that the properties of the object must be decorated with the JsonConverterAttribute like this:
    ///     [JsonConverter(typeof(RawJsonConverter))]
    ///     public string EncodedJsonProperty { get; set; }
    /// </summary>
    public class RawJsonConverter : JsonConverter
    {
        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                var value = serializer.Deserialize<String>(reader).Trim();
                return JToken.Parse(value).ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("Could not parse JSON from string in RawJsonConverter.", ex);
            }
        }

        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteRawValue((string)value);
        }

        /// <inheritdoc />
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(string);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM