java list去掉空格,使用Java从XML元素中删除空格

I have a JSON as follows

String str = {'Emp name' : 'JSON','Emp id' : 1,'Salary' : 20997.00}

I want to covert this JSON to XML using java.My java code is here.

JSON json= JSONSerializer.toJSON(str);

XMLSerializer xmlSerializer = new XMLSerializer();

//To Skip the white space from XML data and not from XML Element (By default it does)

xmlSerializer.setSkipWhitespace(true);

//To set type of xml element If it true, it will be type

xmlSerializer.setTypeHintsCompatibility(true);

xmlSerializer.setRootName("book");

String xml = xmlSerializer.write( json );

System.out.println(xml);

I am getting an output if I pass the xml without any space between XML element (i.e Emp name as Empname and Emp id as Empid). I want to remove the whitespace from XML element and not from XML Element content.

解决方案

I decompiled and checked json-lib(2.4) and xom (1.2.5) libraies. Unfortunately there is no such pre/post processors or handlers regarding to key.

This applies both when constructing JSON or building XML as well.

Seems like there is no other way to manually fix keys of JSON. So please check below snippet:

public static void main(String[] args) {

String str = "{'Emp name' : 'JSON','Emp id' : 1,'Salary' : 20997.00, " +

"'manager' : {'first name':'hasan', 'last name' : 'kahraman'}," +

"'co workers': [{'first name':'john', 'last name' : 'wick'}, " +

"{'first name':'albert', 'last name' : 'smith'}]}";

JsonConfig config = new JsonConfig();

JSON json = JSONSerializer.toJSON(str, config);

fixJsonKey(json);

XMLSerializer xmlSerializer = new XMLSerializer();

//To Skip the white space from XML data and not from XML Element (By default it does)

xmlSerializer.setSkipWhitespace(true);

//To set type of xml element If it true, it will be type

xmlSerializer.setTypeHintsCompatibility(true);

xmlSerializer.setRootName("book");

String xml = xmlSerializer.write(json);

System.out.println(xml);

}

private static void fixJsonKey(Object json) {

if (json instanceof JSONObject) {

JSONObject jsonObject = (JSONObject) json;

List keyList = new LinkedList(jsonObject.keySet());

for (String key : keyList) {

if (!key.matches(".*[\\s\t\n]+.*")) {

Object value = jsonObject.get(key);

fixJsonKey(value);

continue;

}

Object value = jsonObject.remove(key);

String newKey = key.replaceAll("[\\s\t\n]", "");

fixJsonKey(value);

jsonObject.accumulate(newKey, value);

}

} else if (json instanceof JSONArray) {

for (Object aJsonArray : (JSONArray) json) {

fixJsonKey(aJsonArray);

}

}

}

Output is as below:

1

JSON

20997.0

john

wick

albert

smith

hasan

kahraman

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值