{"nodeId":3,"parentId":1,"descript":"CC","children":[{"nodeId":4,"parentId":3,"descript":"DD","children":null}]}]}.
2. fastJson转换示例:
public static Object parseJavaObject(String jsonStr,Class clazz){
return JSON.parseObject(jsonStr, clazz);
}
PropertiesUtil pp =new PropertiesUtil("f:/properties.properties");
String json1 = pp.getProperty("json1");
VIPInformationBean user = (VIPInformationBean)parseJavaObject(json1,VIPInformationBean.class);
其中:
A. PropertiesUtil 类(见最后附1内容,代码来自网络,感谢原作者),为自定义的从配置文件中读取JSON字串的类。
B. VIPInformationBean 类,为自定义的,需要将JSON字符串转成目标JAVA对象的类。
public class VIPInformationBean {
private int nodeId;
private int parentId;
private String descript;
private List<VIPInformationBean> children;
<请自行生成以上变量的get和set方法,可以使用eclipse等工具快速生成>
}
3. 需要导入的包
import com.alibaba.fastjson.JSON;
4.完成以上功能前,需要先将fastjson的JAR包导入项目中。
附1内容:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class PropertiesUtil {
private Properties props;
private String fileName;
public PropertiesUtil(String fileName){
this.fileName=fileName;
readProperties(fileName);
}
private void readProperties(String fileName) {
try {
props = new Properties();
FileInputStream fis =new FileInputStream(fileName);
props.load(fis);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取某个属性
*/
public String getProperty(String key){
return props.getProperty(key);
}
/**
* 获取所有属性,返回一个map,不常用
* 可以试试props.putAll(t)
*/
public Map getAllProperty(){
Map map=new HashMap();
Enumeration enu = props.propertyNames();
while (enu.hasMoreElements()) {
String key = (String) enu.nextElement();
String value = props.getProperty(key);
map.put(key, value);
}
return map;
}
/**
* 在控制台上打印出所有属性,调试时用。
*/
public void printProperties(){
props.list(System.out);
}
/**
* 写入properties信息
*/
public void writeProperties(String key, String value) {
try {
OutputStream fos = new FileOutputStream(fileName);
props.setProperty(key, value);
// 将此 Properties 表中的属性列表(键和元素对)写入输出流
props.store(fos, "『comments』Update key:" + key);
} catch (IOException e) {
}
}
public static void main(String[] args) {
PropertiesUtil util=new PropertiesUtil("src/config.properties");
System.out.println("ip=" + util.getProperty("ip"));
util.writeProperties("key", "value0");
}