簡體   English   中英

為Windows Phone反序列化動態json

[英]deserializing dynamic json for windows phone

以下是我的Json數據的c#類:

[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; }

}

出現問題的是Deal類,每次解析數據時,它都有不同的成員數(即child_1,child_2,.... child_x)。 所以我的問題是如何使動態類Deal,以便可以相應地反序列化json。 我正在使用json.net在Visual Studio 2010中為Windows Phone應用程序開發反序列化json。是否可以完成創建動態類的操作,或者是否有其他方法可以反序列化json。

在此先感謝您的幫助。

這是json數據:

{"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"}]}}

在Json.Net中,您可以將“ deal”屬性定義為Dictionary<string,List<Child12>>以實現此目標。

此代碼適用於您的示例。

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; }

    }
}

JSON中是否有最大數量的子代,或者可以是任意數量? 如果JSON每次每次僅包含子代的不同子集,則可以使用包含所有這些出現的超集的目標類,並且目標對象將只包含未誘導子代的null。 據我所知,這就是反序列化的工作方式。

當然,您需要向目標類中的所有這些子級屬性添加適當的屬性,以指示在反序列化數據時並非所有成員都是必需的。

我已經找到了使用動態json的解決方案: 使用JSon.NET對動態數據反序列化JSON

使用了simplejson,之前使用過json.net。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM