简体   繁体   中英

deserializing dynamic json for windows phone

Following is my c# class of Json data::

[DataContract]
 public class RootObject
 {
           [DataMember(Name="success")]
           public bool success { get; set; }
          [DataMember(Name="deal")]
          public Deal deal { get; set; }
}
[DataContract]
public class Deal
{
    [DataMember(Name = "child_1")]
    public List<Child12> child_1 { get; set; }
    [DataMember(Name = "child_2")]    
    public List<Child12> child_2 { get; set; }
    [DataMember(Name = "child_3")]
    public List<Child12> child_3 { get; set; }
    [DataMember(Name = "child_4")]
    public List<Child12> child_4 { get; set; }
    [DataMember(Name = "child_5")]
    public List<Child12> child_5 { get; set; }
    [DataMember(Name = "child_6")]    
    public List<Child12> child_6 { get; set; }
}

[DataContract]
public class Child12
{
    [DataMember(Name = "scan_count")]
    public string scan_count { get; set; }
    [DataMember(Name = "id")]
    public string id { get; set; }
    [DataMember(Name = "merchant_id")]
    public string merchant_id { get; set; }
    [DataMember(Name = "company_id")]
    public string company_id { get; set; }
    [DataMember(Name = "points_to_earn")]
    public string points_to_earn { get; set; }
    [DataMember(Name = "equivalent_points")]
    public string equivalent_points { get; set; }
    [DataMember(Name = "description")]
    public string description { get; set; }
    [DataMember(Name = "deal_city")]
    public string deal_city { get; set; }
    [DataMember(Name = "price")]
    public string price { get; set; }
    [DataMember(Name = "guidelines")]
    public string guidelines { get; set; }
    [DataMember(Name = "business_name")]
    public string business_name { get; set; }
    [DataMember(Name = "b_type")]
    public string b_type { get; set; }
    [DataMember(Name = "b_image")]
    public string b_image { get; set; }

}

The problem arises is the Deal class, every time when the data is parsed it has different no of members(ie child_1, child_2,.... child_x). So my question is how to make dynamic class Deal so that the json can be deserialized accordingly. I am using json.net for deserializing json for windows phone app development in Visual studio 2010. Can it be done to create dynamic class or is there any other method to deserialize json.

Thanks in advance for your help.

here is the json data:

{"success":true,"deal":{"child_1":[{"scan_count":"7","id":"110","merchant_id":"244","company_id":"85","points_to_earn":"10","equivalent_points":"$25 in Purchases","description":"Receive a $25 gift card after 10 purchases of $25 or more!","deal_city":"Minneapolis","price":"25","guidelines":"Only one point may be earned per visit. ","business_name":"Bone Adventure","b_type":"7","b_image":"Bone-thumb1.jpg","b_state":"MN","b_line1":" 312 E Hennepin","b_line2":"","latitude":"44.9881339","longitude":"-93.2556557","b_zipcode":"55414","start_date":"2012-04-15","end_date":"2012-12-23","user_id":"389","deal_id":"110","state_name":"Minnesota","city_name":"Twin Cities","business_type":"Pet","c_image":"bone-main1.jpg","c_about":"Bone Adventure loves our neighborhoods and the communities of pets and their people that we serve! Our passion is offering a place for people to find high quality pet care basics and the healthiest pet foods and treats. Bone Adventure is a place where customers can come to feel the quality of our materials, hear the squeak of our toys, fit their dogs in the perfect size of apparel, and even sample a treat or two.","c_line1":" 312 E Hennepin","c_line2":"","c_zipcode":"55414","c_website":"www.BoneAdventure.com","c_phone":"(612) 378-0211"}],"child_2":[{"scan_count":"2","id":"101","merchant_id":"175","company_id":"77","points_to_earn":"10","equivalent_points":"$50 in Purchases","description":"Receive a $50 gift card after 10 purchases of $50 or more!","deal_city":"Minneapolis","price":"50","guidelines":"Only one point may be earned per visit.","business_name":"Parc Boutique","b_type":"3","b_image":"ParcBoutique-thumb1.jpg","b_state":"MN","b_line1":"320 E Hennepin Ave","b_line2":"","latitude":"44.9882846","longitude":"-93.2552125","b_zipcode":"55414","start_date":"2012-03-20","end_date":"2013-03-20","user_id":"389","deal_id":"101","state_name":"Minnesota","city_name":"Twin Cities","business_type":"Shopping","c_image":"ParcBoutique-Main1.jpg","c_about":"Smitten with casual-chic style? You\u2019ll fall in love with Parc Boutique. We\u2019re a posh boutique for women and men who covet fresh, fun styles and premium basics.","c_line1":"320 E Hennepin Ave","c_line2":"","c_zipcode":"55414","c_website":"www.parcboutique.com","c_phone":"612.353.4966"}],"child_3":[{"scan_count":"1","id":"105","merchant_id":"179","company_id":"81","points_to_earn":"10","equivalent_points":"Specialty Coffee Drink","description":"Get your caffeine fix! After purchasing any 10 specialty drinks (lattes or cappuccinos) we treat next!","deal_city":"Minneapolis ","price":"4","guidelines":"Only one point may be earned per visit. ","business_name":"Corner Coffee","b_type":"1","b_image":"Corner_Coffee_Thumb4.jpg","b_state":"MN","b_line1":"514 N 3rd St","b_line2":"","latitude":"44.985867","longitude":"-93.276115","b_zipcode":"55401","start_date":"2012-03-20","end_date":"2013-03-20","user_id":"389","deal_id":"105","state_name":"Minnesota","city_name":"Twin Cities","business_type":"Restaurants","c_image":"Latte.jpg","c_about":"Although it\u2019s not even on the corner, Corner Coffee is popular neighborhood coffee shop that also serves tasty breakfast and lunch dishes. It\u2019s laid back and relaxed atmosphere has locals coming back day after day. Check it out!","c_line1":"514 N 3rd St","c_line2":"","c_zipcode":"55401","c_website":"www.yourcornercoffee.com","c_phone":"612.338.2002"}],"child_4":[{"scan_count":"2","id":"98","merchant_id":"172","company_id":"74","points_to_earn":"4","equivalent_points":"Full Price Massage","description":"Receive any half hour fusion FREE with your next service after purchasing four full priced massage treatments!","deal_city":"Minneapolis ","price":"50","guidelines":"1. Only one point awarded per visit\n2. Fusions are not stand-alone services, therefore must be booke","business_name":"Sabai Body Temple","b_type":"5","b_image":"Sabai-thumb.jpg","b_state":"MN","b_line1":"2753 Hennepin Avenue South","b_line2":"","latitude":"44.9521528","longitude":"-93.298233","b_zipcode":"55408","start_date":"2012-03-20","end_date":"2013-03-20","user_id":"389","deal_id":"98","state_name":"Minnesota","city_name":"Twin Cities","business_type":"Health\/Spa","c_image":"Sabai-main.jpg","c_about":"Fully trained, professional massage therapists,specialising in Eastern-inspired massage and Alternative Medicine. We have the best selection of couple's massage and treatments in the Twin Cities and are proud to offer chemical-free massage treatments and spa rituals.","c_line1":"2753 Hennepin Avenue South","c_line2":"","c_zipcode":"55408","c_website":"www.sabaibodytemple.com","c_phone":"612.872.8354"}],"child_5":[{"scan_count":"5","id":"100","merchant_id":"174","company_id":"76","points_to_earn":"10","equivalent_points":"$10\/$15","description":"Receive any 1 menu item FREE after 10 purchases of $10 during the hours of 11:30-5PM, or $15 during the hours of 5:30-close.","deal_city":"Minneapolis ","price":"10","guidelines":"No rules here...just come in and enjoy yourself! ","business_name":"The Public House","b_type":"1","b_image":"Public_House_logo.png","b_state":"MN","b_line1":"700 Washington Avenue N","b_line2":"","latitude":"44.987999","longitude":"-93.2766709","b_zipcode":"55401","start_date":"2012-03-20","end_date":"2013-03-20","user_id":"389","deal_id":"100","state_name":"Minnesota","city_name":"Twin Cities","business_type":"Restaurants","c_image":"The_Public_House_-_Main1.jpg","c_about":"The Public House is one of those neighborhood joints that's easy to come back to, time and time again. It's great cuisine, craft beers and affordable prices make it a Warehouse District favorite!","c_line1":"700 Washington Avenue N","c_line2":"","c_zipcode":"55401","c_website":"www.thepublichousempls.com","c_phone":"612.455.1213"}],"child_6":[{"scan_count":"1","id":"106","merchant_id":"184","company_id":"82","points_to_earn":"6","equivalent_points":"Any Treatment Purchase","description":"FREE Microdermabrasion after the purchase of any 6 treatments!","deal_city":"Eden Prairie","price":"150","guidelines":"Only one point may be earned per visit. ","business_name":"Envy Skin Clinic","b_type":"5","b_image":"Envy_Skin_-_Thumb3.jpg","b_state":"MN","b_line1":"300 Prairie Center Drive","b_line2":"","latitude":"44.8571219","longitude":"-93.421224","b_zipcode":"55344","start_date":"2012-03-21","end_date":"2013-03-21","user_id":"389","deal_id":"106","state_name":"Minnesota","city_name":"Twin Cities","business_type":"Health\/Spa","c_image":"envy.jpg","c_about":"At ENVY Skin Clinic we want it to be all about you. We bring you a \"boutique\" clinic atmosphere where you receive personal attention and state-of-the-art laser services. Once you begin treatment, you will feel completely at ease with our highly experienced medical professionals.","c_line1":"300 Prairie Center Drive","c_line2":"","c_zipcode":"55344","c_website":"www.envyskinclinic.com","c_phone":"952.983.4588"}]}}

In Json.Net you can define "deal" property as Dictionary<string,List<Child12>> to achive such goal.

This code works on your example.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DeserializeObject();
            Console.ReadKey();
        }

        private static async void DeserializeObject()
        {
            using (var reader = new StreamReader("TextFile1.txt"))
            {
                var jsonSerializerSettings = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Auto};
                var value = await reader.ReadToEndAsync();
                var result = JsonConvert.DeserializeObject<RootObject>(value, jsonSerializerSettings);
            }
        }
    }

    public class RootObject
    {
        public bool success { get; set; }
        public Dictionary<string, List<Child12>> deal { get; set; }
    }

    public class Child12
    {
        public string scan_count { get; set; }
        public string id { get; set; }
        public string merchant_id { get; set; }
        public string company_id { get; set; }
        public string points_to_earn { get; set; }
        public string equivalent_points { get; set; }
        public string description { get; set; }
        public string deal_city { get; set; }
        public string price { get; set; }
        public string guidelines { get; set; }
        public string business_name { get; set; }
        public string b_type { get; set; }
        public string b_image { get; set; }

    }
}

Is there a maximum number of children in the JSON, or it could be arbitrary number? If the JSON just contains different subset of children each time, you can use target class containing super set of all these occurrences and the target object will just contain nulls for not induced children. This is how deserialization works as far as I know.

Of course you need to add proper attributes to all these children properties in the target class to signal that not all members are required when deserializing the data.

I had found the solution for using dynamic json: Deserializing JSON using JSon.NET with dynamic data

Used simplejson which previously was using json.net..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM