JSON 데이터 변환

2722 단어 json
예: 패키지 가져오기(struts-2.1.8.1\lib에서 참조)
  json-lib-2.1.jar commons-collections-3.2.jar commons-beanutils-1.7.0.jar commons-lang-2.3.jar commons-logging-1.0.4.jar ezmorph-1.0.3.jar public class ActionName { private String namespace; private String actionname; get、set  } public class Authorization{ private int category; private List<ActionName> list; get、set  } 

json-lib-2.1.jarcommons-collections-3.2.jarcommons-beanutils-1.7.0.jarcommons-lang-2.3.jarcommons-logging-1.0.4.jarezmorph-1.0.3.jarpublic class ActionName {private String namespace;private String actionname;get, set 약}?public class Authorization {private int category;private List list;get, set 약}?
1) 객체를 json 문자열로 변환
public class PojoToJson {public static void main(String[] args) {ActionName o=new ActionName();o.setActionname("test");o.setNamespace("/space");JSONObject jo = JSONObject.fromObject(o);System.err.println(jo.toString());?ActionName o1=new ActionName();o1.setActionname("test1");o1.setNamespace("/space");List list=new ArrayList();list.add(o);list.add(o1);Authorization a=new Authorization();a.setCategory(1);a.setList(list);JSONObject json = JSONObject.fromObject(a);System.err.println(json.toString());}}
2) json 문자열을 객체로 변환
?
authorization.txt 내용
authorization=[{"category": "1", "list": [{"namespace": "/user", "actionname"//전의가 필요합니다: "login"}, {"namespace": "/user", "actionname": "register"}]},{"category":"2","list":[{"namespace":"/user","actionname":"listUser"},{"namespace":"/user","actionname":"updateUser"}]}]public class JsonToPojo {public static void main(String[] args) throws IOException {
Properties properties = new Properties();properties.load(new FileInputStream("E:\\authorization.txt"));String authorization=(String) properties.get("authorization");System.err.println("jsonString:"+authorization);
JSONArray ja = JSONArray.fromObject(authorization);Map>classMap = new HashMap>();classMap.put("list", ActionName.class);Listlist = JSONArray.toList(ja, Authorization.class,classMap);
for(Authorization c:list){System.err.println("category:"+c.getCategory());for(ActionName n:c.getList()){System.err.println("actionname:"+n.getActionname());System.err.println("namespace:"+n.getNamespace());}}}}

좋은 웹페이지 즐겨찾기