在这种情况下,如何解析JSON数组中存在的值

时间:2014-11-21 16:11:36

标签: java

我正在尝试解析此JSON

{
    "details": {
        "Service Tax": [
            {
                "tax_order": 3,
                "inclusive": [
                    {
                        "Discount": 1,
                        "Service Charge": 1
                    }
                ]
            }
        ],
        "VAT": [
            {
                "tax_order": 3,
                "inclusive": [
                    {
                        "Discount": 1,
                        "Service Charge": 1,
                        "Item": 1
                    }
                ]
            }
        ]
    },
    "vendor_id": 1
}

是否可以提取数组中存在的值的字段。

例如,如果服务税,我需要提取折扣和服务费

例如,如果增值税,我需要获取折扣,服务费和项目

package test;

import org.json.JSONArray;
import org.json.JSONObject;

public class Tester {


    public static void main(String args[]) throws Exception
    {

        String json = "{\r\n" + 
                "    \"details\": {\r\n" + 
                "        \"Service Tax\": [\r\n" + 
                "            {\r\n" + 
                "                \"tax_order\": 3,\r\n" + 
                "                \"inclusive\": [\r\n" + 
                "                    {\r\n" + 
                "                        \"Discount\": 1,\r\n" + 
                "                        \"Service Charge\": 1\r\n" + 
                "                    }\r\n" + 
                "                ]\r\n" + 
                "            }\r\n" + 
                "        ],\r\n" + 
                "        \"VAT\": [\r\n" + 
                "            {\r\n" + 
                "                \"tax_order\": 3,\r\n" + 
                "                \"inclusive\": [\r\n" + 
                "                    {\r\n" + 
                "                        \"Discount\": 1,\r\n" + 
                "                        \"Service Charge\": 1,\r\n" + 
                "                        \"Item\": 1\r\n" + 
                "                    }\r\n" + 
                "                ]\r\n" + 
                "            }\r\n" + 
                "        ]\r\n" + 
                "    },\r\n" + 
                "    \"vendor_id\": 1\r\n" + 
                "}";


         String[] json_order = new String[]{"Service Tax", "VAT"};

            JSONObject inputRqstJson = new JSONObject(json);
            JSONObject details_json = inputRqstJson.getJSONObject("details");

                for(String tax_name : json_order)
                {
                JSONArray tax_nameJarray = details_json.getJSONArray(tax_name);
                System.out.println(tax_nameJarray);
                }

    }
}

0 个答案:

没有答案