反序列化JSON以获取几个参数

时间:2014-05-15 11:20:30

标签: java json json-deserialization

我无法理解我得到的JSON响应。 这是JSON(它有点大,我提前为我的c / p道歉)我只需要3个属性:名称,价格和类别。我会在字符串的底部放置那些,但我不确定它是否更容易获得嵌套的..所以,实际上,更简单的是,那将是我的优先权:)

{
"results":
[{
"sitedetails":[{
            "latestoffers":[{
                                "id":"6JotT9dMmWeYoi0UqKESoO",
                                "price":"1167.74",
                                "firstrecorded_at":1349396400,
                                "lastrecorded_at":1399787300,
                                "seller":"Walmart",
                                "availability":"Out of Stock",
                                "currency":"USD"
                            }],
                                "offers_count":1,
                                "name":"walmart.com",
                                "recentoffers_count":1,
                                "sku":"20604679",
                                "url":"http://www.walmart.com/ip/20604679"
            },
                {   
             "latestoffers":[{
                                "id":"5QTxsmf7GwYQWca60UQyAy",
                                "price":"1134.99",
                                "firstrecorded_at":1350835696,
                                "lastrecorded_at":1382836600,
                                "seller":"Newegg",
                                "availability":"OUT OF STOCK. [BBX: Buy Box]",
                                "currency":"USD"
                            },
                            {
                                "id":"3l8ZNONJHyWoMsaO8AGoCQ",
                                "shipping":"14.30",
                                "price":"1134.99",
                                "firstrecorded_at":1360613800,
                                "lastrecorded_at":1362344900,
                                "seller":"newegg.com",
                                "availability":"Deactivated. This item is currently out of stock and it may or may not be restocked. [BBX: Buy Box]",
                                "currency":"USD"
                            }
                            ],
                    "offers_count":2,
                    "name":"newegg.com",
                    "recentoffers_count":1,
                    "sku":"N82E16834214948",
                    "url":"http://www.newegg.com/Product/Product.aspx?Item=N82E16834214948"
                },
                {
            "latestoffers":[{
                                "id":"13XfN5eSpiAOyWmiKs6Kcs",
                                "price":"1026.00",
                                "firstrecorded_at":1379730300,
                                "lastrecorded_at":1379730300,
                                "seller":"Cheapgoodsz.com",
                                "availability":"Available",
                                "currency":"USD"
                            }],
                    "offers_count":1,
                    "name":"cheapgoodsz.com",
                    "recentoffers_count":1,
                    "sku":"8409",
                    "url":"http://www.cheapgoodsz.com/toshiba-toshiba-z830s8301-laptop-p-8409.html"
                }
            ],
"model":"PT225U 004004;Z830 S8301",
"weight":"1120373.15",
"price_currency":"USD",
"gtins":["00883974958450"],
"mpn":"PT225U-00400EN",
"sem3_help":"To view image links and additional merchants for this product, please upgrade your plan.",
"cat_id":"23130",
"height":"15.24",
"name":"Toshiba Portege Z830-S8301 13.3-Inch Netbook Computer",
"features":
            {
            "LCD Backlight Technology":"LED backlight",
            "64-bit Computing":"Yes",
            "Interfaces":"VGA LAN Microphone input Headphone output 2 x USB 2.0 USB 3.0 HDMI",
            "Run Time":"Up to 8.3 hour(s)",
            "CPU":"Intel Core i5 (2nd Gen) 2557M / 1.7 GHz",
            "Output":"45 Watt , 19 V , 2.37 A",
            "Ethernet Controller":"Intel 82579LM",
            "EPEAT Compliant":"EPEAT Gold",
            "Memory Card Reader":"Yes ( SD Card, miniSD, SDHC Memory Card, microSD )",
            "Chipset":"Mobile Intel QM67 Express",
            "Slots Qty":"1",
            "Microsoft Office Preloaded":"Includes a pre-loaded image of select Microsoft Office 2010 suites. Purchase an Office 2010 Product Key Card or disc to activate preloaded software on this PC.","Other Features":"Security lock slot (cable lock sold separately), Toshiba EasyGuard, Intel Active Management Technology (iAMT), USB Sleep-and-charge ports",
            "Wireless":"802.11n, Bluetooth 3.0 HS",
            "Sound":"Stereo speakers , microphone",
            "ENERGY STAR Qualified":"Yes",
            "Network Interface":"Gigabit Ethernet",
            "Input":"AC 120/230 V ( 50/60 Hz )",
            "System Type":"Ultrabook",
            "Image Aspect Ratio":"16:9",
            "Operating System":"Microsoft Windows 7 Professional (32/64 bits)",
            "Resolution":"1.3 Megapixel",
            "RAM":"4 GB ( 1 x 2 GB + 2 GB (soldered) )",
            "Camera":"Integrated webcam",
            "Max Operating Temperature":"95 Ã\u201a°F",
            "Max Allocated RAM Size":"1696 MB",
            "Cache":"L3 - 3 MB",
            "Localization":"United States",
            "Humidity Range Operating":"20 - 80% (non-condensing)",
            "Service & Support Details":"Limited warranty - 3 years Limited warranty - battery - 1 year",
            "Compliant Standards":"RoHS",
            "Number of Cores":"Dual-Core",
            "Graphics Processor":"Intel HD Graphics 3000",
            "Interface":"Serial ATA-300",
            "Wireless Controller":"Intel Centrino Advanced-N 6230",
            "Security":"Trusted Platform Module (TPM 1.2) Security Chip , fingerprint reader",
            "Speed":"1333 MHz",
            "Memory Allocation Technology":"Dynamic Video Memory Technology",
            "Min Operating Temperature":"41 Ã\u201a°F",
            "Service & Support":"3 years warranty",
            "Audio Features":"MaxxAudio 3",
            "Max RAM Supported":"6 GB",
            "Capacity":"47 Wh",
            "Hard Drive":"128 GB SSD",
            "Software Included":"Adobe Acrobat Reader, Google Toolbar, Adobe Flash Player, Skype, Toshiba Assist, Toshiba Recovery DiskCreator, Windows Live Essentials, Toshiba PC Health Monitor, Toshiba Eco Utility, Toshiba ReelTime, Toshiba Bulletin Board, Google Chrome, Toshiba Media Controller, Microsoft Silverlight, Toshiba Disc Creator, Toshiba Fingerprint Utility, Toshiba Security Assist, Toshiba Value Added Package, Windows Live Messenger, Face Recognition software, Windows Live Photo Gallery, Windows Live Mail, Windows Live Writer, Microsoft Windows Media Player 12, Toshiba Service Station, Toshiba Hardware Setup Utility, Toshiba Web Camera Application, Toshiba Online Backup (30 days trial), Windows Live Movie Maker, Microsoft Office 2010 Starter, Toshiba App Place, Toshiba Book Place, Toshiba HDD/SSD Alert, Toshiba Sleep Utility, Toshiba Password Utility, Microsoft Internet Explorer 9.0, Toshiba Device Access Control, Toshiba Resolution+, Norton Internet Security 2012 (30 days trial), Intel Wireless Display Technology 2.1",
            "Max Turbo Speed":"2.7 GHz",
            "Technology":"8-cell lithium ion",
            "Widescreen":"Yes"
            },
"length":"227.08",
"created_at":1347480704,
"geo":["usa"],
"width":"315.98",
"upc":"883974958450",
"ean":"0883974958450",
"category":"Netbooks",
"price":"1026.00",
"updated_at":1399832844,
"color":"Silver",
"manufacturer":"Toshiba America Information Systems",
"images_total":0,
"brand":"Toshiba",
"sem3_id":"2iTwoIQGhEKMiW62moMy0u",
"offers_total":74
}]
,"total_results_count":1,
"results_count":1,
"code":"OK",
"offset":0
}

我认为我在这里做了一些完全错误的事情。我搜索了一些可以帮助我的答案,最后我制作了自己的解串器:

public class ProductInfo {


String name;

String category;
Double price;

public ProductInfo(){}
public ProductInfo(String name, String category, Double price){
    this.name=name;
    this.category=category;
    this.price=price;
}

public ProductInfo deserialize(JSONObject results, Type type, JsonDeserializationContext context) throws JsonParseException {



    return new ProductInfo(
            results.getString("name").toString(),
            results.getString("category").toString(),
            results.getDouble("price"));

        // USED THIS WHILE I WAS USING GSON 
        //  jobject.get("name").getAsString(),
        //  jobject.get("category").getAsString(), 
        //  jobject.get("price").getAsDouble());
}

以下是我在main中使用这个反序列化器的方法:

JSONObject results = products.getProducts();     //I get the JSONObject from a link here.
ProductInfo pi = new ProductInfo();
pi.deserialize(results, type, context );

如果有人能解释我是如何获得我需要的参数,那将是非常棒的。感谢您阅读我的帖子。

2 个答案:

答案 0 :(得分:0)

可能是因为“results”是一个数组并且在另一个对象中,而“name”在“result”中。所以你需要做这样的事情。

JSONObject response = products.getProducts();
JSONObject result = response.getJSONArray("results").get(0);
ProductInfo pi = new ProductInfo();
pi.deserialize(result, type, context );

答案 1 :(得分:0)

我研究了JSON语法并意识到我有一个JSONArray只有一个JSONObject,它由几个其他JSONArrays组成(还包括其他JSONObjects等)。 我只需要在提到的JSONArray中使用索引为0的第一个JSONObject。所以这是我的新解串器:

public ProductInfo deserialize(JSONObject results, Type type, JsonDeserializationContext context) throws JsonParseException {

JSONArray resultsArray = results.getJSONArray("results");

JSONObject objekt = resultsArray.getJSONObject(0);
String name = objekt.get("name").toString();
String category = objekt.get("category").toString();
String price =  objekt.get("price").toString();


return new ProductInfo(name, category,  price);
}

当我尝试获取名称/值对时,当我尝试在我的主要内容中打印它时,它只会给我nullnullnull

System.out.println(pi.getName()+pi.getCategory()+pi.getPrice());

Any1知道为什么值为null