Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When deserializing JSON with C#/NewtonSoft, can you flatten some of the results?

Tags:

json

c#

json.net

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.

like image 408
NibblyPig Avatar asked Jan 22 '13 09:01

NibblyPig


1 Answers

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.

like image 183
Pablissimo Avatar answered Oct 27 '22 00:10

Pablissimo