java解析JSON
在www.json.org上公布了很多Java下的json解析工具,其中json-lib比较简单,下面源代码是解析和构造JSON的演示程序。 这是使用json-lib的程序: [code="java"] package com.jshx.httptransfer.utils; import java.util.HashMap; import java.util.Map; import net.sf.json.JSONObject; public class test { public static void main(String[] args) { String json ="{\"name\":\"reiz\"}"; JSONObject jsonObj = JSONObject.fromObject(json); String name = jsonObj.getString("name"); jsonObj.put("initial", name.substring(0, 1).toUpperCase()); String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" }; jsonObj.put("likes", likes); Map ingredients = new HashMap(); ingredients.put("apples", "3kg"); ingredients.put("sugar", "1kg"); ingredients.put("pastry", "2.4kg"); ingredients.put("bestEaten", "outdoors"); jsonObj.put("ingredients",ingredients); System.out.println(jsonObj); Map tt = jsonObj.getJSONObject("ingredients"); System.out.println(tt.get("apples")); } } [/code] 要依赖ezmorph和commons的lang、logging、beanutils、collections等组件。 [code="java"] // 填写需要过滤的JSON字段 String[] excludes = new String[] { "dbTableName" }; List filters = new ArrayList(); filters.add(new IgnoreNullFieldPropertyFilter()); //JSON json = JSONSerializer .toJSON(resultMap, JsonUtils.configJson(excludes, filters, "yyyy-MM-dd HH:mm:ss")); JSONObject detailArray = JSONObject.fromObject(jshxWorkReply,JsonUtils.configJson(excludes, filters, "yyyy-MM-dd HH:mm:ss")); [/code]