search
HomeBackend DevelopmentXML/RSS TutorialJSON-lib framework, converting JSON and XML is no longer difficult

Json-lib can convert Java objects into json format strings, and can also convert Java objects into xml format documents. It can also convert json strings into Java objects or xml strings into Java objects. .

1. Preparation

1. First of all Go to the official download json-lib toolkit

Download address:

http://www.php.cn/

The latest version is version 2.4. In this example v2.3 is used; json-lib also requires the following dependency packages:

jakarta commons-lang 2.5

jakarta commons-beanutils 1.8.0

jakarta commons-collections 3.2.1

jakarta commons-logging 1.1.1

ezmorph 1.0.6

Official website: http://www.php.cn/

Then add the following jar package to the project:

JSON-lib framework, converting JSON and XML is no longer difficult

Of course you can also use the 2.4 json-lib library

You can check out the official provision here Example:

http://www.php.cn/

Since the example introduced this time requires the junit tool, you also need to add the junit jar file, the version is 4.8.2 Version, download address: http://www.php.cn/

If you still don’t know what JSON is? Then you should be able to take a look at http://www.php.cn/

2. The code of the JavaBean to be converted is as follows:


package com.hoo.entity;
 <br>
public class Student {
    private int id;
    private String name;
    private String email;
    private String address;
    private Birthday birthday;
 <br>
    //setter、getter
    public String toString() {
        return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
    }
}
 <br>

##Birthday.java


##
package com.hoo.entity;

 <br>
public class Birthday {
    private String birthday;
    <br>
    public Birthday(String birthday) {
        super();
        this.birthday = birthday;
    }
    //setter、getter
    public Birthday() {}
    <br>
    @Override
    public String toString() {
        return this.birthday;
    }
}

Note that the above getter and setter methods are omitted, build them yourself.

3. Create a new JsonlibTest test class. The basic code is as follows:


##

package com.hoo.test;
 <br>

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONFunction;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.beanutils.PropertyUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.hoo.entity.Birthday;
import com.hoo.entity.Student;
 <br>
/**
 * <b>function:</b> 用json-lib转换java对象到JSON字符串
 * 读取json字符串到java对象,序列化jsonObject到xml
 * json-lib-version: json-lib-2.3-jdk15.jar
 * 依赖包:
 * commons-beanutils.jar
 * commons-collections-3.2.jar
 * ezmorph-1.0.3.jar
 * commons-lang.jar
 * commons-logging.jar
 * @author hoojo
 * @createDate Nov 28, 2010 2:28:39 PM
 * @file JsonlibTest.java
 * @package com.hoo.test
 * @project WebHttpUtils
 * @blog http://www.php.cn/
 * @email hoojo_@126.com
 * @version 1.0
 */
@SuppressWarnings({ "deprecation", "unchecked" })
public class JsonlibTest {
    private JSONArray jsonArray = null;
    private JSONObject jsonObject = null;
    <br>
    private Student bean = null;
    <br>
    @Before
    public void init() {
        jsonArray = new JSONArray();
        jsonObject = new JSONObject();
        <br>
        bean = new Student();
        bean.setAddress("address");
        bean.setEmail("email");
        bean.setId(1);
        bean.setName("haha");
        Birthday day = new Birthday();
        day.setBirthday("2010-11-22");
        bean.setBirthday(day);
    }
    <br>
    @After
    public void destory() {
        jsonArray = null;
        jsonObject = null;
        bean = null;
        System.gc();
    }
    <br>
    public final void fail(String string) {
        System.out.println(string);
    }
    <br>
    public final void failRed(String string) {
        System.err.println(string);
    }
    <br>
}

上面的init会在每个方法之前运行,destory会在每个方法完成后执行。分别用到了junit的@Before、@After注解,如果你对junit的这些注解不是很了解,可以看看junit官方的测试用例的example和doc;

JSONObject是将Java对象转换成一个json的Object形式,JSONArray是将一个Java对象转换成json的Array格式。

那什么是json的Object形式、Array形式?

用通俗易懂的方法将,所谓的json的Object形式就是一个花括号里面存放的如JavaMap的键值对,如:{name:’hoojo’, age: 24};

那么json的Array形式呢?

就是中括号,括起来的数组。如:[ ‘json’, true, 22];

如果你还想了解更多json方面的知识,请看:http://www.php.cn/

除了上面的JSONArray、JSONObject可以将Java对象转换成JSON或是相反,将JSON字符串转换成Java对象,还有一个对象也可以完成上面的功能,它就是JSONSerializer;下面我们就来看看它们是怎么玩转Java对象和JSON的。

二、 Java对象序列化成JSON对象

1、 将JavaObject转换吃JSON字符串

在JsonlibTest中添加如下代码:


/*=========================Java Object >>>> JSON String ===========================*/
/**
 * <b>function:</b>转Java Bean对象到JSON
 * @author hoojo
 * @createDate Nov 28, 2010 2:35:54 PM
 */
@Test
public void writeEntity2JSON() {
    fail("==============Java Bean >>> JSON Object==================");
    fail(JSONObject.fromObject(bean).toString());
    fail("==============Java Bean >>> JSON Array==================");
    fail(JSONArray.fromObject(bean).toString());//array会在最外层套上[]
    fail("==============Java Bean >>> JSON Object ==================");
    fail(JSONSerializer.toJSON(bean).toString());
    <br>
    fail("========================JsonConfig========================");
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.registerJsonValueProcessor(Birthday.class, new JsonValueProcessor() {
        public Object processArrayValue(Object value, JsonConfig jsonConfig) {
            if (value == null) {
                return new Date();
            }
            return value;
        }
 <br>
        public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
            fail("key:" + key);
            return value + "##修改过的日期";
        }
 <br>
    });
    jsonObject = JSONObject.fromObject(bean, jsonConfig);
    <br>
    fail(jsonObject.toString());
    Student student = (Student) JSONObject.toBean(jsonObject, Student.class);
    fail(jsonObject.getString("birthday"));
    fail(student.toString());
    <br>
    fail("#####################JsonPropertyFilter############################");
    jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
        public boolean apply(Object source, String name, Object value) {
            fail(source + "%%%" + name + "--" + value);
            //忽略birthday属性
            if (value != null && Birthday.class.isAssignableFrom(value.getClass())) {
                return true;
            }
            return false;
        }
    });
    fail(JSONObject.fromObject(bean, jsonConfig).toString());
    fail("#################JavaPropertyFilter##################");
    jsonConfig.setRootClass(Student.class);
    jsonConfig.setJavaPropertyFilter(new PropertyFilter() {
        public boolean apply(Object source, String name, Object value) {
            fail(name + "@" + value + "#" + source);
            if ("id".equals(name) || "email".equals(name)) {
                value = name + "@@";
                return true;
            }
            return false;
        }
    });
    //jsonObject = JSONObject.fromObject(bean, jsonConfig);
    //student = (Student) JSONObject.toBean(jsonObject, Student.class);
    //fail(student.toString());
    student = (Student) JSONObject.toBean(jsonObject, jsonConfig);
    fail("Student:" + student.toString());
}

fromObject将Java对象转换成json字符串,toBean将json对象转换成Java对象;

上面方法值得注意的是使用了JsonConfig这个对象,这个对象可以在序列化的时候对JavaObject的数据进行处理、过滤等

上面的jsonConfig的registerJsonValueProcessor方法可以完成对象值的处理和修改,比如处理生日为null时,给一个特定的值。同样setJsonPropertyFilter和setJavaPropertyFilter都是完成对转换后的值的处理。

运行上面的代码可以在控制台看到如下结果:


==============Java Bean >>> JSON Object==================
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}
==============Java Bean >>> JSON Array==================
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}]
==============Java Bean >>> JSON Object ==================
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"haha"}
========================JsonConfig========================
key:birthday
{"address":"address","birthday":"2010-11-22##修改过的日期","email":"email","id":1,"name":"haha"}
2010-11-22##修改过的日期
haha#1#address#null#email
#####################JsonPropertyFilter############################
haha#1#address#2010-11-22#email%%%address--address
haha#1#address#2010-11-22#email%%%birthday--2010-11-22
haha#1#address#2010-11-22#email%%%email--email
haha#1#address#2010-11-22#email%%%id--1
haha#1#address#2010-11-22#email%%%name--haha
{"address":"address","email":"email","id":1,"name":"haha"}
#################JavaPropertyFilter##################
address@address#null#0#null#null#null
birthday@2010-11-22##修改过的日期#null#0#address#null#null
email@email#null#0#address#null#null
id@1#null#0#address#null#null
name@haha#null#0#address#null#null
Student:haha#0#address#null#null

2、 将JavaList集合转换吃JSON字符串


/**
 * <b>function:</b>转换Java List集合到JSON
 * @author hoojo
 * @createDate Nov 28, 2010 2:36:15 PM
 */
@Test
public void writeList2JSON() {
    fail("==============Java List >>> JSON Array==================");
    List<student> stu = new ArrayList<student>();</student></student>
    stu.add(bean);
    bean.setName("jack");
    stu.add(bean);
    fail(JSONArray.fromObject(stu).toString());
    fail(JSONSerializer.toJSON(stu).toString());
}

运行此方法后,可以看到控制台输出:


==============Java List >>> JSON Array==================
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]
[{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},
{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"}]

如果你是转换List集合,一定得用JSONArray或是JSONSrializer提供的序列化方法。如果你用JSONObject.fromObject方法转换List会出现异常,通常使用JSONSrializer这个JSON序列化的方法,它会自动识别你传递的对象的类型,然后转换成相应的JSON字符串。

3、 将Map集合转换成JSON对象


/**
 * <b>function:</b>转Java Map对象到JSON
 * @author hoojo
 * @createDate Nov 28, 2010 2:37:35 PM
 */
@Test
public void writeMap2JSON() {
    Map<string> map = new HashMap<string>();</string></string>
    map.put("A", bean);
    <br>
    bean.setName("jack");
    map.put("B", bean);
    map.put("name", "json");
    map.put("bool", Boolean.TRUE);
    map.put("int", new Integer(1));
    map.put("arr", new String[] { "a", "b" });
    map.put("func", "function(i){ return this.arr[i]; }");
    fail("==============Java Map >>> JSON Object==================");
    fail(JSONObject.fromObject(map).toString());
    fail("==============Java Map >>> JSON Array ==================");
    fail(JSONArray.fromObject(map).toString());
    fail("==============Java Map >>> JSON Object==================");
    fail(JSONSerializer.toJSON(map).toString());
}

上面的Map集合有JavaBean、String、Boolean、Integer、以及Array和js的function函数的字符串。

运行上面的程序,结果如下:


==============Java Map >>> JSON Object==================
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}
==============Java Map >>> JSON Array ==================
[{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}]
==============Java Map >>> JSON Object==================
{"arr":["a","b"],"A":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"int":1,
"B":{"address":"address","birthday":{"birthday":"2010-11-22"},"email":"email","id":1,"name":"jack"},"name":"json",
"func":function(i){ return this.arr[i]; },"bool":true}

4、 将更多类型转换成JSON


/**
 * <b>function:</b>  转换更多数组类型到JSON
 * @author hoojo
 * @createDate Nov 28, 2010 2:39:19 PM
 */
@Test
public void writeObject2JSON() {
    String[] sa = {"a", "b", "c"};
    fail("==============Java StringArray >>> JSON Array ==================");
    fail(JSONArray.fromObject(sa).toString());
    fail(JSONSerializer.toJSON(sa).toString());
    fail("==============Java boolean Array >>> JSON Array ==================");
    boolean[] bo = { true, false, true };
    fail(JSONArray.fromObject(bo).toString());
    fail(JSONSerializer.toJSON(bo).toString());
    Object[] o = { 1, "a", true, 'A', sa, bo };
    fail("==============Java Object Array >>> JSON Array ==================");
    fail(JSONArray.fromObject(o).toString());
    fail(JSONSerializer.toJSON(o).toString());
    fail("==============Java String >>> JSON ==================");
    fail(JSONArray.fromObject("['json','is','easy']").toString());
    fail(JSONObject.fromObject("{'json':'is easy'}").toString());
    fail(JSONSerializer.toJSON("['json','is','easy']").toString());
    fail("==============Java JSONObject >>> JSON ==================");
    jsonObject = new JSONObject()
        .element("string", "JSON")
        .element("integer", "1")
        .element("double", "2.0")
        .element("boolean", "true");
    fail(JSONSerializer.toJSON(jsonObject).toString());
    <br>
    fail("==============Java JSONArray >>> JSON ==================");
    jsonArray = new JSONArray()
        .element( "JSON" )
        .element( "1" )
        .element( "2.0" )
        .element( "true" );
    fail(JSONSerializer.toJSON(jsonArray).toString());
    <br>
    fail("==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================");
    List input = new ArrayList();
    input.add("JSON");
    input.add("1");
    input.add("2.0");
    input.add("true");
    JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );
    Object[] output = (Object[]) JSONSerializer.toJava(jsonArray, jsonConfig);
    System.out.println(output[0]);
    <br>
    fail("==============Java JSONFunction >>> JSON ==================");
    String str = "{'func': function( param ){ doSomethingWithParam(param); }}";
    JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str);
    JSONFunction func = (JSONFunction) jsonObject.get("func");
    fail(func.getParams()[0]);
    fail(func.getText() );
}

运行后结果如下:


==============Java StringArray >>> JSON Array ==================
["a","b","c"]
["a","b","c"]
==============Java boolean Array >>> JSON Array ==================
[true,false,true]
[true,false,true]
==============Java Object Array >>> JSON Array ==================
[1,"a",true,"A",["a","b","c"],[true,false,true]]
[1,"a",true,"A",["a","b","c"],[true,false,true]]
==============Java String >>> JSON ==================
["json","is","easy"]
{"json":"is easy"}
["json","is","easy"]
==============Java JSONObject >>> JSON ==================
{"string":"JSON","integer":"1","double":"2.0","boolean":"true"}
==============Java JSONArray >>> JSON ==================
["JSON","1","2.0","true"]
==============Java JSONArray JsonConfig#setArrayMode >>> JSON ==================
JSON
==============Java JSONFunction >>> JSON ==================
param
doSomethingWithParam(param);

这里还有一个JSONFunction的对象,可以转换JavaScript的function。可以获取方法参数和方法体。同时,还可以用JSONObject、JSONArray构建Java对象,完成Java对象到JSON字符串的转换。

三、 JSON对象反序列化成Java对象

1、 将json字符串转成Java对象


private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"}," +
        "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
/**
 * <b>function:</b>将json字符串转化为java对象
 * @author hoojo
 * @createDate Nov 28, 2010 3:01:16 PM
 */
@Test
public void readJSON2Bean() {
    fail("==============JSON Object String >>> Java Bean ==================");
    jsonObject = JSONObject.fromObject(json);
    Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
    fail(stu.toString());
}

运行后,结果如下:


==============JSON Object String >>> Java Bean ==================
tom#22#chian#2010-11-22#email@123.com

2、 将json字符串转换成动态Java对象(MorphDynaBean)


private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 <br>
@Test
public void readJSON2DynaBean() {
    try {
        fail("==============JSON Object String >>> Java MorphDynaBean ==================");
        JSON jo = JSONSerializer.toJSON(json);
        Object o = JSONSerializer.toJava(jo);//MorphDynaBean
        fail(PropertyUtils.getProperty(o, "address").toString());
        jsonObject = JSONObject.fromObject(json);
        fail(jsonObject.getString("email"));
        o = JSONSerializer.toJava(jsonObject);//MorphDynaBean
        fail(PropertyUtils.getProperty(o, "name").toString());
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}

转换后的对象Object是一个MorphDynaBean的动态JavaBean,通过PropertyUtils可以获得指定的属性的值。

运行后结果如下:


==============JSON Object String >>> Java MorphDynaBean =============
chian
email@123.com
tom

3、 将json字符串转成Java的Array数组


private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 <br>
@Test
public void readJSON2Array() {
    try {
        fail("==============JSON Arry String >>> Java Array ==================");
        json = "[" + json + "]";
        jsonArray = JSONArray.fromObject(json);
        fail("#%%%" + jsonArray.get(0).toString());
        Object[] os = jsonArray.toArray();
        System.out.println(os.length);
        <br>
        fail(JSONArray.fromObject(json).join(""));
        fail(os[0].toString());
        Student[] stus = (Student[]) JSONArray.toArray(jsonArray, Student.class);
        System.out.println(stus.length);
        System.out.println(stus[0]);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

运行的结果如下:


==============JSON Arry String >>> Java Array ==================
#%%%{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
1
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}
1
tom#22#chian#2010-11-22#email@123.com

4、 将JSON字符串转成Java的List集合


private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 <br>
@Test
public void readJSON2List() {
    try {
        fail("==============JSON Arry String >>> Java List ==================");
        json = "[" + json + "]";
        jsonArray = JSONArray.fromObject(json);
        List<student> list = JSONArray.toList(jsonArray, Student.class);</student>
        System.out.println(list.size());
        System.out.println(list.get(0));
        <br>
        list = JSONArray.toList(jsonArray);
        System.out.println(list.size());
        System.out.println(list.get(0));//MorphDynaBean
    } catch (Exception e) {
        e.printStackTrace();
    }
}

运行后结果如下:


==============JSON Arry String >>> Java List ==================
1
tom#22#chian#2010-11-22#email@123.com
1
net.sf.ezmorph.bean.MorphDynaBean@141b571[
  {id=22, birthday=net.sf.ezmorph.bean.MorphDynaBean@b23210[
  {birthday=2010-11-22}
], address=chian, email=email@123.com, name=tom}
]

5、 将json字符串转换成Collection接口


private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";
 <br>
@Test
public void readJSON2Collection() {
    try {
        fail("==============JSON Arry String >>> Java Collection ==================");
        json = "[" + json + "]";
        jsonArray = JSONArray.fromObject(json);
        Collection<student> con = JSONArray.toCollection(jsonArray, Student.class);</student>
        System.out.println(con.size());
        Object[] stt = con.toArray();
        System.out.println(stt.length);
        fail(stt[0].toString());
        <br>
    } catch (Exception e) {
        e.printStackTrace();
    }
}

刚才上面的将json转换成list提示该方法过时,这里有toCollection,可以用此方法代替toList方法;运行后结果如下:


==============JSON Arry String >>> Java Collection ==================
1
1
tom#22#chian#2010-11-22#email@123.com

6、 将json字符串转换成Map集合


@Test
public void readJSON2Map() {
    try {
        fail("==============JSON Arry String >>> Java Map ==================");
        json = "{\"arr\":[\"a\",\"b\"],\"A\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"int\":1,"+
        "\"B\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+
        "\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"name\":\"json\",\"bool\":true}";
        jsonObject = JSONObject.fromObject(json);
        Map<string>> clazzMap = new HashMap<string>>();</string></string>
        clazzMap.put("arr", String[].class);
        clazzMap.put("A", Student.class);
        clazzMap.put("B", Student.class);
        Map<string> mapBean = (Map) JSONObject.toBean(jsonObject, Map.class, clazzMap);</string>
        System.out.println(mapBean);
        <br>
        Set<string> set = mapBean.keySet();</string>
        Iterator<string> iter = set.iterator();</string>
        while (iter.hasNext()) {
            String key = iter.next();
            fail(key + ":" + mapBean.get(key).toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

运行后结果如下:


==============JSON Arry String >>> Java Map ==================
{A=jack#1#address#2010-11-22#email, arr=[a, b], B=jack#1#address#2010-11-22#email, int=1, name=json, bool=true}
A:jack#1#address#2010-11-22#email
arr:[a, b]
B:jack#1#address#2010-11-22#email
int:1
name:json
bool:true

四、 JSON-libXML的支持

1、 将Java对象到XML


/*============================Java Object >>>>> XML ==========================*/
/**
 * <b>function:</b> 转换Java对象到XML
 * 需要额外的jar包:xom.jar
 * @author hoojo
 * @createDate Nov 28, 2010 2:39:55 PM
 */
@Test
public void writeObject2XML() {
    XMLSerializer xmlSerializer = new XMLSerializer();
    fail("==============Java String Array >>> XML ==================");
    //xmlSerializer.setElementName("bean");
    fail(xmlSerializer.write(JSONArray.fromObject(bean)));
    String[] sa = {"a", "b", "c"};
    fail("==============Java String Array >>> XML ==================");
    fail(xmlSerializer.write(JSONArray.fromObject(sa)));
    fail("==============Java boolean Array >>> XML ==================");
    boolean[] bo = { true, false, true };
    fail(xmlSerializer.write(JSONArray.fromObject(bo)));
    fail(xmlSerializer.write(JSONSerializer.toJSON(bo)));
    Object[] o = { 1, "a", true, 'A', sa, bo };
    fail("==============Java Object Array >>> JSON Array ==================");
    fail(xmlSerializer.write(JSONArray.fromObject(o)));
    fail(xmlSerializer.write(JSONSerializer.toJSON(o)));
    fail("==============Java String >>> JSON ==================");
    fail(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
    fail(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
    fail(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
}

主要运用的是XMLSerializer的write方法,这个方法可以完成java对象到xml的转换,不过你很容易就可以看到这个xml序列化对象,需要先将java对象转成json对象,然后再将json转换吃xml文档。

运行后结果如下:

==============Java String Array >>> XML ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e class="object">
<address type="string">address</address><birthday class="object"><birthday type="string">2010-11-22</birthday></birthday>
<email type="string">email</email><id type="number">1</id><name type="string">haha</name>
</e></a>
 
==============Java String Array >>> XML ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="string">a</e><e type="string">b</e><e type="string">c</e></a>
 
==============Java boolean Array >>> XML ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="boolean">true</e><e type="boolean">false</e><e type="boolean">true</e></a>
 
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="boolean">true</e><e type="boolean">false</e><e type="boolean">true</e></a>
 
==============Java Object Array >>> JSON Array ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="number">1</e><e type="string">a</e><e type="boolean">true</e><e type="string">A</e><e class="array">
<e type="string">a</e><e type="string">b</e><e type="string">c</e></e><e class="array"><e type="boolean">true</e>
<e type="boolean">false</e><e type="boolean">true</e></e></a>
 
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="number">1</e><e type="string">a</e><e type="boolean">true</e><e type="string">A</e><e class="array">
<e type="string">a</e><e type="string">b</e><e type="string">c</e></e><e class="array"><e type="boolean">true</e>
<e type="boolean">false</e><e type="boolean">true</e></e></a>
 
==============Java String >>> JSON ==================
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="string">json</e><e type="string">is</e><e type="string">easy</e></a>
 
<?xml version="1.0" encoding="UTF-8"?>
<o><json type="string">is easy</json></o>
 
<?xml version="1.0" encoding="UTF-8"?>
<a><e type="string">json</e><e type="string">is</e><e type="string">easy</e></a>

上面的节点名称有点乱,你可以通过setElementName设置节点名称

2、 将XML转换成Java对象


/*============================XML String >>>>> Java Object ==========================*/
/**
 * <b>function:</b>转换xml文档到java对象
 * @author hoojo
 * @createDate Nov 28, 2010 3:00:27 PM
 */
@Test
public void readXML2Object() {
    XMLSerializer xmlSerializer = new XMLSerializer();
    fail("============== XML >>>> Java String Array ==================");
    String[] sa = {"a", "b", "c"};
    jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(sa)));
    fail(jsonArray.toString());
    <br>
    String[] s = (String[]) JSONArray.toArray(jsonArray, String.class);
    fail(s[0].toString());
    <br>
    fail("============== XML >>>> Java boolean Array ==================");
    boolean[] bo = { true, false, true };
    jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(bo)));
    bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);
    fail(bo.toString());
    System.out.println(bo[0]);
    <br>
    jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(bo)));
    bo = (boolean[]) JSONArray.toArray(jsonArray, boolean.class);
    fail(bo.toString());
    System.out.println(bo[0]);
    <br>
    fail("==============Java Object Array >>> JSON Array ==================");
    Object[] o = { 1, "a", true, 'A', sa, bo };
    jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject(o)));
    System.out.println(jsonArray.getInt(0));
    System.out.println(jsonArray.get(1));
    System.out.println(jsonArray.getBoolean(2));
    jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON(o)));
    System.out.println(jsonArray.get(4));
    System.out.println(jsonArray.getJSONArray(5).get(0));
    System.out.println(jsonArray.get(5));
    <br>
    fail("==============Java String >>> JSON ==================");
    jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONArray.fromObject("['json','is','easy']")).toString());
    s = (String[]) JSONArray.toArray(jsonArray, String.class);
    fail(s[0].toString());
    jsonObject = (JSONObject) xmlSerializer.read(xmlSerializer.write(JSONObject.fromObject("{'json':'is easy'}")).toString());
    Object obj = JSONObject.toBean(jsonObject);
    System.out.println(obj);
    jsonArray = (JSONArray) xmlSerializer.read(xmlSerializer.write(JSONSerializer.toJSON("['json','is','easy']")).toString());
    s = (String[]) JSONArray.toArray(jsonArray, String.class);
    fail(s[1].toString());
}

主要运用到XMLSerializer的read方法,将xml内容读取后,转换成Java对象。运行后结果如下:


============== XML >>>> Java String Array ==================
["a","b","c"]
a
============== XML >>>> Java boolean Array ==================
[Z@15856a5
true
[Z@79ed7f
true
==============Java Object Array >>> JSON Array ==================
1
a
true
["a","b","c"]
true
["true","false","true"]
==============Java String >>> JSON ==================
json
net.sf.ezmorph.bean.MorphDynaBean@c09554[
  {json=is easy}
]
is

3、 将xml的字符串内容,转换成Java的Array对象


@Test
public void testReadXml2Array() {
    String str = "<a>" +</a>
          "<e>" +</e>
          "return matrix[i][j];" +
          "" +
        "";
    JSONArray json = (JSONArray) new XMLSerializer().read(str);
    fail(json.toString());
}

上面是一段xml字符串格式的文档,将其转换为JSONArray对象。转换后结果如下:


[function(i,j){ return matrix[i][j]; }]

就是一个数组;

 以上就是JSON-lib框架,转换JSON、XML不再困难的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Decoding RSS: The XML Structure of Content FeedsDecoding RSS: The XML Structure of Content FeedsApr 17, 2025 am 12:09 AM

The XML structure of RSS includes: 1. XML declaration and RSS version, 2. Channel (Channel), 3. Item. These parts form the basis of RSS files, allowing users to obtain and process content information by parsing XML data.

How to Parse and Utilize XML-Based RSS FeedsHow to Parse and Utilize XML-Based RSS FeedsApr 16, 2025 am 12:05 AM

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS Documents: How They Deliver Your Favorite ContentRSS Documents: How They Deliver Your Favorite ContentApr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

Building Feeds with XML: A Hands-On Guide to RSSBuilding Feeds with XML: A Hands-On Guide to RSSApr 14, 2025 am 12:17 AM

The steps to build an RSSfeed using XML are as follows: 1. Create the root element and set the version; 2. Add the channel element and its basic information; 3. Add the entry element, including the title, link and description; 4. Convert the XML structure to a string and output it. With these steps, you can create a valid RSSfeed from scratch and enhance its functionality by adding additional elements such as release date and author information.

Creating RSS Documents: A Step-by-Step TutorialCreating RSS Documents: A Step-by-Step TutorialApr 13, 2025 am 12:10 AM

The steps to create an RSS document are as follows: 1. Write in XML format, with the root element, including the elements. 2. Add, etc. elements to describe channel information. 3. Add elements, each representing a content entry, including,,,,,,,,,,,. 4. Optionally add and elements to enrich the content. 5. Ensure the XML format is correct, use online tools to verify, optimize performance and keep content updated.

XML's Role in RSS: The Foundation of Syndicated ContentXML's Role in RSS: The Foundation of Syndicated ContentApr 12, 2025 am 12:17 AM

The core role of XML in RSS is to provide a standardized and flexible data format. 1. The structure and markup language characteristics of XML make it suitable for data exchange and storage. 2. RSS uses XML to create a standardized format to facilitate content sharing. 3. The application of XML in RSS includes elements that define feed content, such as title and release date. 4. Advantages include standardization and scalability, and challenges include document verbose and strict syntax requirements. 5. Best practices include validating XML validity, keeping it simple, using CDATA, and regularly updating.

From XML to Readable Content: Demystifying RSS FeedsFrom XML to Readable Content: Demystifying RSS FeedsApr 11, 2025 am 12:03 AM

RSSfeedsareXMLdocumentsusedforcontentaggregationanddistribution.Totransformthemintoreadablecontent:1)ParsetheXMLusinglibrarieslikefeedparserinPython.2)HandledifferentRSSversionsandpotentialparsingerrors.3)Transformthedataintouser-friendlyformatsliket

Is There an RSS Alternative Based on JSON?Is There an RSS Alternative Based on JSON?Apr 10, 2025 am 09:31 AM

JSONFeed is a JSON-based RSS alternative that has its advantages simplicity and ease of use. 1) JSONFeed uses JSON format, which is easy to generate and parse. 2) It supports dynamic generation and is suitable for modern web development. 3) Using JSONFeed can improve content management efficiency and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment