当前位置:懂科普 >

IT科技

> java jsonobject

java jsonobject

1、JSONObject简介:

JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包。

2、项目环境:

system:win7 myeclipse:6.5 tomcat:5.0 JDK:开发环境和编译用的都是1.5。

项目结构如下:

java jsonobject

3、JSONObject:A JSONObject is an unordered collection of name/value pairs.是一个final类,继承了Object,实现了JSON接口。

构造方法如下:

JSONObject();创建一个空的JSONObject对象

JSONObject(boolean isNull);创建一个是否为空的JSONObject对象

普通方法如下:

fromBean(Object bean);静态方法,通过一个pojo对象创建一个JSONObject对象

fromJSONObject(JSONObject object);静态方法,通过另外一个JSONObject对象构造一个JSONObject对象

fromJSONString(JSONString string);静态方法,通过一个JSONString创建一个JSONObject对象

toString();把JSONObject对象转换为json格式的字符串

iterator();返回一个Iterator对象来遍历元素

接下来就是一些put/get方法,需要普通的get方法和pot方法做一下强调说明,API中是这样描述的:

A get method returns a value if one can be found, and throws an exception if one cannot be found. An opt method returns a default value instead of throwing an exception, and so is useful for obtaining optional values.

java jsonobject 第2张

4、JSONArray:A JSONArray is an ordered sequence of values.是一个final类,继承了Object,实现了JSON接口。

构造方法如下:

JSONArray();构造一个空的JSONArray对象

普通方法如下:

fromArray(Object[] array);静态方法,通过一个java数组创建一个JSONArray对象

fromCollection(Collection collection);静态方法,通过collection集合对象创建一个JSONArray对象

fromString(String string);静态方法,通过一个json格式的字符串构造一个JSONArray对象

toString();把JSONArray对象转换为json格式的字符串

iterator();返回一个Iterator对象来遍历元素

接下来同样是put/get方法……

5、XMLSerializer:Utility class for transforming JSON to XML an back.一个继承自Object的类

构造方法如下:

XMLSerializer();创建一个XMLSerializer对象

普通方法如下:

setRootName(String rootName);设置转换的xml的根元素名称

setTypeHintsEnabled(boolean typeHintsEnabled);设置每个元素是否显示type属性

write(JSON json);把json对象转换为xml,默认的字符编码是UTF-8,

需要设置编码可以用write(JSON json, String encoding)

java jsonobject 第3张

对XML和JSON字符串各列一个简单的例子:

JSON:

{"password":"123456","username":"张三"}

xml

<?xml version="1.0" encoding="UTF-8"?>
<user_info>

<password>123456</password>

<username>张三</username>

</user_info>

标签: java jsonobject
  • 文章版权属于文章作者所有,转载请注明 https://dongkepu.com/itkeji/d3kzy5.html