• Java JSON入门


    一、所需jar包 

    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

    下载地址:

    http://json-lib.sourceforge.net/
    http://ezmorph.sourceforge.net/
    http://morph.sourceforge.net/
    http://www.docjar.com

     

    二、举例(json官网 :http://json-lib.sourceforge.net/usage.html)

      1、from beans to json

    	public class Person {
    		private String username;
    		private String password;
    	}
    	@Test
    	public void demo1() {
    		Person person1 = new Person("aaa", "aaa");
    		Person person2 = new Person("bbb", "bbb");
    		List<Person> list = new ArrayList<Person>();
    		list.add(person1);
    		list.add(person2);
    		JSONArray.fromObject(list);
    		JSONArray jsonArray = JSONArray.fromObject(list);   
    		System.out.println( jsonArray.toString());  
    	}
         //[{"password":"aaa","username":"aaa"},{"password":"bbb","username":"bbb"}]

      from json to beans

    class MyBean{  
       private List data;  
       // getters & setters  
    }  
    class Person{  
       private String name;  
       // getters & setters  
    }   
    String json = "{'data':[{'name':'Wallace'},{'name':'Grommit'}]}";  
    Map classMap = new HashMap();  
    classMap.put( "data", Person.class );  
    MyBean bean = JSONObject.toBean( JSONObject.fromObject(json), MyBean.class, classMap );  

     2、from bean to json

    class MyBean{  
       private String name = "json";  
       private int pojoId = 1;  
       private char[] options = new char[]{'a','f'};  
       private String func1 = "function(i){ return this.options[i]; }";  
       private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");  
      
       // getters & setters  
       ...  
    }  
      
    JSONObject jsonObject = JSONObject.fromObject( new MyBean() );  
    System.out.println( jsonObject );  
    /* prints 
      {"name":"json","pojoId":1,"options":["a","f"], 
      "func1":function(i){ return this.options[i];}, 
      "func2":function(i){ return this.options[i];}} 
    */  
    

       from json to bean

    String json = "{bool:true,integer:1,string:"json"}";  
    JSONObject jsonObject = JSONObject.fromObject( json );  
    BeanA bean = (BeanA) JSONObject.toBean( jsonObject, BeanA.class );  
    

      

  • 相关阅读:
    学习小记: Kaggle Learn
    eclipse 一些快捷键
    Map接口
    学习笔记
    泛型方法 类 接口
    TreeSet
    xml
    Java笔试题目-my
    迭代器三种遍历方法
    线程请求其他线程资源
  • 原文地址:https://www.cnblogs.com/zhumengke/p/8782944.html
Copyright © 2020-2023  润新知