Pascal case dynamic properties with Json.NET

前端 未结 4 812
一整个雨季
一整个雨季 2020-12-06 15:57

This is what I have:

using Newtonsoft.Json;

var json = \"{\\\"someProperty\\\":\\\"some value\\\"}\";
dynamic deserialized = JsonConvert.DeserializeObject(j         


        
相关标签:
4条回答
  • 2020-12-06 16:42

    I can't help but feel that this isn't a good idea. It seems like you're trying to preserve a coding convention, but at the expense of maintaining fidelity between the wire format (the JSON structs) and your logic classes. This can cause confusion for developers who expect the JSON classes to be preserved, and might cause issues if you also need, or will need in the future, to re-serialize this data into the same JSON format.

    That said, this probably can be achieved by creating the .NET classes ahead of time, then using the DeserializeObject(string value, JsonSerializerSettings settings) overload, passing it a JsonSerializerSettings with the Binder property set. You will also need to write a custom SerializationBinder in which you manually define the relationship between your JSON class and your predefined .NET class.

    It may be possible to generate Pascal-cased classes in runtime without predefining them, but I haven't delved deep enough into the JSON.NET implementation for that. Perhaps one of the other JsonSerializerSettings settings, like passing a CustomCreationConverter, but I'm not sure of the details.

    0 讨论(0)
  • 2020-12-06 16:55

    I agree with Avner Shahar-Kashtan. You shouldn't be doing this, especially if you have no control over the JSON.

    That said, it can be done with the use of a ExpandoObject and a custom ExpandoObjectConverter. JSON.NET already provides a ExpandoObjectConverter so with some little adjustments you have what you want.

    Notice the //CHANGED comments inside the code snippet to show you where I changed it.

    public class CamelCaseToPascalCaseExpandoObjectConverter : JsonConverter
    {
      //CHANGED
      //the ExpandoObjectConverter needs this internal method so we have to copy it
      //from JsonReader.cs
      internal static bool IsPrimitiveToken(JsonToken token) 
      {
          switch (token)
          {
              case JsonToken.Integer:
              case JsonToken.Float:
              case JsonToken.String:
              case JsonToken.Boolean:
              case JsonToken.Null:
              case JsonToken.Undefined:
              case JsonToken.Date:
              case JsonToken.Bytes:
                  return true;
              default:
                  return false;
          }
      }
    
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      // can write is set to false
    }
    
    /// <summary>
    /// Reads the JSON representation of the object.
    /// </summary>
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
    /// <param name="objectType">Type of the object.</param>
    /// <param name="existingValue">The existing value of object being read.</param>
    /// <param name="serializer">The calling serializer.</param>
    /// <returns>The object value.</returns>
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
      return ReadValue(reader);
    }
    
    private object ReadValue(JsonReader reader)
    {
      while (reader.TokenType == JsonToken.Comment)
      {
        if (!reader.Read())
          throw new Exception("Unexpected end.");
      }
    
      switch (reader.TokenType)
      {
        case JsonToken.StartObject:
          return ReadObject(reader);
        case JsonToken.StartArray:
          return ReadList(reader);
        default:
          //CHANGED
          //call to static method declared inside this class
          if (IsPrimitiveToken(reader.TokenType))
            return reader.Value;
    
          //CHANGED
          //Use string.format instead of some util function declared inside JSON.NET
          throw new Exception(string.Format(CultureInfo.InvariantCulture, "Unexpected token when converting ExpandoObject: {0}", reader.TokenType));
      }
    }
    
    private object ReadList(JsonReader reader)
    {
      IList<object> list = new List<object>();
    
      while (reader.Read())
      {
        switch (reader.TokenType)
        {
          case JsonToken.Comment:
            break;
          default:
            object v = ReadValue(reader);
    
            list.Add(v);
            break;
          case JsonToken.EndArray:
            return list;
        }
      }
    
      throw new Exception("Unexpected end.");
    }
    
    private object ReadObject(JsonReader reader)
    {
      IDictionary<string, object> expandoObject = new ExpandoObject();
    
      while (reader.Read())
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            //CHANGED
            //added call to ToPascalCase extension method       
            string propertyName = reader.Value.ToString().ToPascalCase();
    
            if (!reader.Read())
              throw new Exception("Unexpected end.");
    
            object v = ReadValue(reader);
    
            expandoObject[propertyName] = v;
            break;
          case JsonToken.Comment:
            break;
          case JsonToken.EndObject:
            return expandoObject;
        }
      }
    
      throw new Exception("Unexpected end.");
    }
    
    /// <summary>
    /// Determines whether this instance can convert the specified object type.
    /// </summary>
    /// <param name="objectType">Type of the object.</param>
    /// <returns>
    ///     <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
    /// </returns>
    public override bool CanConvert(Type objectType)
    {
      return (objectType == typeof (ExpandoObject));
    }
    
    /// <summary>
    /// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
    /// </summary>
    /// <value>
    ///     <c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
    /// </value>
    public override bool CanWrite
    {
      get { return false; }
    }
    }
    

    A simple string to Pascal Case converter. Make it smarter if you need to.

    public static class StringExtensions
    {
        public static string ToPascalCase(this string s)
        {
            if (string.IsNullOrEmpty(s) || !char.IsLower(s[0]))
                return s;
    
            string str = char.ToUpper(s[0], CultureInfo.InvariantCulture).ToString((IFormatProvider)CultureInfo.InvariantCulture);
    
            if (s.Length > 1)
                str = str + s.Substring(1);
    
            return str;
        }
    }
    

    Now you can use it like this.

    var settings = new JsonSerializerSettings()
                       {
                           ContractResolver = new CamelCasePropertyNamesContractResolver(),
                           Converters = new List<JsonConverter> { new CamelCaseToPascalCaseExpandoObjectConverter() }
                       };
    
    var json = "{\"someProperty\":\"some value\"}";
    
    dynamic deserialized = JsonConvert.DeserializeObject<ExpandoObject>(json, settings);
    
    Console.WriteLine(deserialized.SomeProperty); //some value
    
    var json2 = JsonConvert.SerializeObject(deserialized, Formatting.None, settings);
    
    Console.WriteLine(json == json2); //true
    

    The ContractResolver CamelCasePropertyNamesContractResolver is used when serializing the object back to JSON and makes it Camel case again. This is also provided by JSON.NET. If you don't need this you can omit it.

    0 讨论(0)
  • 2020-12-06 16:56

    you have to change your JSON to, {\"SomeProperty\":\"some value\"}

    0 讨论(0)
  • 2020-12-06 17:04

    For newtonsoft add this attribute to your properties:

    [JsonProperty("schwabFirmId")]
    

    A simpler option (since you just need to do it once per class) if you are up for including MongoDB: try adding a reference to MongoDB.Bson.Serialization.Conventions.

    Then add this in your model constructor:

    var pack = new ConventionPack { new CamelCaseElementNameConvention(), new IgnoreIfDefaultConvention(true) };
                ConventionRegistry.Register("CamelCaseIgnoreDefault", pack, t => true);
    

    Either one will keep your favorite C# properties PascalCased and your json camelCased.

    Deserializing will treat the inbound data as PascalCased and serializing will change it into camelCase.

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