json数据类型转换

目录 一、测试数据 二、Str、JSONObject、JSONArray等互转 三、数据遍历、不规则数据整理 四、JsonString转XML 五、XML转JsonString 六、json转map 七、map转xml 一、测试数据 private static String getJsonData() {

目录

一、测试数据

二、Str、JSONObject、JSONArray等互转

三、数据遍历、不规则数据整理

四、JsonString转XML

五、XML转JsonString

六、json转map

七、map转xml


一、测试数据

private static String getJsonData() {
        return "{\n" +
                "    \"companyNo\": \"C001\",\n" +
                "    \"supplyNo\": \"S001\",\n" +
                "    \"orders\": [\n" +
                "        {\n" +
                "            \"orderNo\": \"aaa001\",\n" +
                "            \"orderType\": \"order001\",\n" +
                "            \"orderAmount\": \"100\",\n" +
                "            \"creatorDate\": \"20020505\",\n" +
                "            \"invoiceAmount\": \"500\",\n" +
                "            \"openItemAmount\": \"700\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"orderNo\": \"ccc002\",\n" +
                "            \"orderType\": \"order002\",\n" +
                "            \"orderAmount\": \"600\",\n" +
                "            \"creatorDate\": \"20010506\",\n" +
                "            \"invoiceAmount\": \"123\",\n" +
                "            \"openItemAmount\": \"456\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
    }

二、Str、JSONObject、JSONArray等互转

private static void json2json(String reqString) {
        reqString = "".equals(reqString) ? null : reqString;
        //string转object对象
        JSONObject reqJson = JSONObject.parseObject(reqString);
        //获取对应字段
        String companyNo = reqJson.getString("companyNo");
        //JSONObject转JSONArray
        String orders = reqJson.getString("orders");
        JSONArray jsonArray = JSONArray.parseArray(orders);

        //jsonObject-json互转
        JSON json = reqJson.getObject("orders", JSON.class);
        String str = json.toJSONString();
        JSONObject jsonObject = JSONObject.parseObject(str);
        JSONArray jsonArray2 = JSONArray.parseArray(str);
        JSONArray dealArray = dealArray(jsonArray);
        System.out.println(reqJson);

        // json格式str转bean
        Bean bean = JSON.parseObject(jsonStr, Bean.class);

        //json格式str转List<bean>
        List<Bean> list = JSON.parseArray(jsonStr, Bean.class);

    }

三、数据遍历、不规则数据整理

//遍历,处理不规则数据
    private static JSONArray dealArray(JSONArray array) {
        JSONArray array2 = new JSONArray();
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            JSONObject jsonObject = new JSONObject();
            for (String key : json.keySet()) {
                jsonObject.put(key, json.get(key).toString().trim());
            }
            array2.add(jsonObject);
        }
        return array2;
    }

四、JsonString转XML

    public static String toXml(Object obj) throws UnsupportedEncodingException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        JAXB.marshal(obj,outputStream);
        return outputStream.toString("utf8");
    }

五、XML转JsonString

    public static Object xmlToParam(String xml,Class<?> clazz) throws JAXBException {
        StringReader reader = new StringReader(xml);
        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return unmarshaller.unmarshal(reader);
    }

六、json转map

public static Map<String, Object> json2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        if(jsonStr != null && !"".equals(jsonStr)){
            //最外层解析
            try {
                Map jsonObject = objectMapper.readValue(jsonStr, Map.class);
                for (Object k : jsonObject.keySet()) {
                    Object v = jsonObject.get(k);
                    //如果内层还是数组的话,继续解析
                    if (v instanceof ArrayList) {
                        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                        Iterator<Map> it = ((ArrayList) v).iterator();
                        while (it.hasNext()) {
                            Map json2 = it.next();
                            list.add(json2Map(objectMapper.writeValueAsString(json2)));
                        }
                        map.put(k.toString(), list);
                    } else {
                        map.put(k.toString(), v);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return map;
        }else{
            return null;
        }
    }

七、map转xml

public static String jsonToXml(Object json, String rootKey) {
    Document document = DocumentHelper.createDocument();
    //设置根节点和命名空间
    QName qName = new QName(rootKey);
    //设置命令空间
    Element element = document.addElement(qName);
    document.setRootElement(element);

    ObjectMapper objectMapper = new ObjectMapper();
    try {
        JsonObject jsonObject = new JsonParser().parse(objectMapper.writeValueAsString(json)).getAsJsonObject();
        toXml(jsonObject, document.getRootElement(), null);
        return document.asXML();
    } catch (Exception e) {
        log.error(e.getMessage());
        throw new AppException(e.getMessage());
    }
}

private static Element toXml(JsonElement jsonElement, Element parentElement, String name) {
    if (jsonElement instanceof JsonArray) {
        //是json数据,需继续解析
        JsonArray sonJsonArray = (JsonArray)jsonElement;
        for (int i = 0; i < sonJsonArray.size(); i++) {
            JsonElement arrayElement = sonJsonArray.get(i);
            toXml(arrayElement, parentElement, name);
        }
    }else if (jsonElement instanceof JsonObject) {
        //说明是一个json对象字符串,需要继续解析
        JsonObject sonJsonObject = (JsonObject) jsonElement;
        Element currentElement = null;
        if (name != null) {
            currentElement = parentElement.addElement(name);
        }
        Set<Map.Entry<String, JsonElement>> set = sonJsonObject.entrySet();
        for (Map.Entry<String, JsonElement> s : set) {
            toXml(s.getValue(), currentElement != null ? currentElement : parentElement, s.getKey());
        }
    }else if (jsonElement.isJsonNull()){
        parentElement.addElement(name);
    }else {
        //说明是一个键值对的key,可以作为节点插入了
        addAttribute(parentElement, name, jsonElement.getAsString());
    }
    return parentElement;
}

private static void addAttribute(Element element, String name, String value) {
    //增加子节点,并为子节点赋值
    if (String.valueOf(name.charAt(0)).equals(StringPool.DASH)){

        // 参数前为 “-”符号的为节点属性 去除“-”符号并添加属性
        String key=name.substring(1);
        if (key.equals("xmlns")){
            Namespace namespace=new Namespace("",value);
            QName qName=new QName(element.getName(),namespace);
            element.setQName(qName);
        }else {
            element.addAttribute(key,value);
        }
    }else if (StringPool.HASH.equals(String.valueOf(name.charAt(0)))){
        element.addText(value);
    }else {
        Element el = element.addElement(name);
        el.addText(value);
    }
}

有用请点赞,养成良好习惯!

疑问交流鼓励请留言!

知秋君
上一篇 2024-08-21 21:48
下一篇 2024-08-21 21:12

相关推荐