如何让Newtonsoft JsonProperty仅用于反序列化,序列化保留属性名?
JsonProperty Only for Deserialization in Newtonsoft.Json Absolutely! You can configure Newtonsoft.Json to use those JsonProperty attributes only for deserialization while outputting clean, properly named properties (like Open, High) during serialization. Here are two reliable approaches:
Approach 1: Use JsonPropertyAccess.Read (Simplest Method)
Newtonsoft.Json's JsonProperty attribute has an Access property that lets you restrict when the attribute is used. Setting it to JsonPropertyAccess.Read tells the serializer to use the custom property name only when reading (deserializing) data, and use the default property name when writing (serializing).
Here's how your entity class would look:
using Newtonsoft.Json; public class StockData { [JsonProperty("1. open", Access = JsonPropertyAccess.Read)] public decimal Open { get; set; } [JsonProperty("2. high", Access = JsonPropertyAccess.Read)] public decimal High { get; set; } }
How it works:
- Deserialization: When parsing the messy JSON (with
"1. open"/"2. high"), Newtonsoft uses the custom property names to map values to yourOpen/Highproperties. - Serialization: When converting the object back to JSON, the serializer ignores the custom property names and uses the default PascalCase names of your class properties (resulting in
"Open"/"High").
Test code:
// Deserialize from messy JSON var rawJson = "{\"1. open\": 99.99, \"2. high\": 102.50}"; var stockData = JsonConvert.DeserializeObject<StockData>(rawJson); // Serialize to clean JSON var cleanJson = JsonConvert.SerializeObject(stockData, Formatting.Indented); // Output will be: // { // "Open": 99.99, // "High": 102.50 // }
Approach 2: Use Private "Deserialization-Only" Properties (For Older Newtonsoft Versions)
If you're using a version of Newtonsoft.Json older than 9.0.1 (where JsonPropertyAccess was introduced), you can use private properties to handle deserialization, while keeping your public properties clean for serialization.
using Newtonsoft.Json; public class StockData { // Public property for serialization public decimal Open { get; set; } // Private property only for deserialization [JsonProperty("1. open")] private decimal OpenFromJson { set => Open = value; } public decimal High { get; set; } [JsonProperty("2. high")] private decimal HighFromJson { set => High = value; } }
How it works:
- Deserialization: Newtonsoft recognizes the private
OpenFromJson/HighFromJsonproperties (thanks to theJsonPropertyattribute) and maps the messy JSON fields to them, which in turn set your publicOpen/Highproperties. - Serialization: The private properties are ignored by default (since they don't have public getters), so the serializer outputs your public
Open/Highproperties with their clean names.
Both methods work reliably—pick the one that fits your Newtonsoft.Json version and coding style!
内容的提问来源于stack exchange,提问作者jay

