If my JSON is:
{ cat: 1, dog: 2, price: { initial: 1, new: 2 } }
Is it possible to deserialize it into a single class that has the properties cat, dog, initialprice, newprice?
Perhaps there is an attribute or way of using the JsonProperty attribute to do this.
I'm using the Newtonsoft.Json library.
The following's a bit rough-and-ready but does what I think you're trying to do. Casing is different to your JSON so it won't roundtrip to your input without some modification.
public class TestClass
{
public decimal Cat { get; set; }
public decimal Dog { get; set; }
[Newtonsoft.Json.JsonProperty]
private Price Price { get; set; }
[Newtonsoft.Json.JsonIgnore]
public decimal InitialPrice
{
get { return this.Price.Initial; }
}
[Newtonsoft.Json.JsonIgnore]
public decimal NewPrice
{
get { return this.Price.New; }
}
}
class Price
{
public decimal Initial { get; set; }
public decimal New { get; set; }
}
Quick test method:
static void Main(string[] args)
{
const string JSON = "{ cat: 1, dog: 2, price: { initial: 1, new: 2 } }";
var deserialised = Newtonsoft.Json.JsonConvert.DeserializeObject<TestClass>(JSON);
var serialised = Newtonsoft.Json.JsonConvert.SerializeObject(deserialised);
}
We've defined a Price type to match what would naturally be deserialised from the price property in your JSON, made it private and then accessed its members using two read-only properties on the TestClass. So - code will see the structure you want (four properties, Cat, Dog, InitialPrice, NewPrice) parsed from the JSON input you defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With