java to Json or Json to JavaBean

今天练习,放这里,以后再补充

这里使用的jar包是 net.sf.json.JSONObject

package yh.test.t1118;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import yh.com.entity.User;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/11/18.
 */
public class Test {

    public static void main(String[] args) {

//        javaToJson();
//        JsonToJava();
        test1();
    }


    /**
     * java to json
     */
    public static void javaToJson(){
        String json = "{\"Json\":\"json\"}";
        JSONObject jsonObj = JSONObject.fromObject(json);
        Map<String, String> user = new HashMap<String, String>();
        user.put("name", "jack");
        user.put("age", "21");
        user.put("sex", "male");
        user.put("job", "students");
        jsonObj.put("users",user);
        System.out.println("------开始输出json------");
        System.out.println(jsonObj);
    }

    /**
     * json to java
     */
    public static void JsonToJava(){
        String json = "{x:'1',y:'2',userId:'112',element:[{id:'123',name:'haha'},{id:'456',name:'hehe'}]}";

//        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject = JSONObject.fromObject(json);

        jsonObject.element("name","limei");
        jsonObject.element("sex","female");
        jsonObject.accumulate("jj", "ss");

        Map<String,String> map = new HashMap<String, String>();
        map.put("a","A");
        map.put("b","B");
        map.put("c","C");
        jsonObject.element("user",map );
//        System.out.println(jsonObject.toString());

        Object o = jsonObject.get("user");

//        System.out.println("==================>"+o);
//        System.out.println("name:"+jsonObject.get("name"));
        JSONArray jsonArray = jsonObject.getJSONArray("element");
        for(int i = 0;i<jsonArray.size();i++){
            System.out.println(jsonArray.get(i));
        }

//        Object object = JSONObject.toBean(jsonObject);
//        System.out.println(object.toString());
    }

    /*******************将json反序列化为javabean*****************/
    public static void test1(){

        String jsonStr = "{x:1,\"userId\":\"112\",element:[{id:'123',name:'haha'},{id:'456',name:'hehe'}]}";
        Map<String,Class<?>> m  = new HashMap<String,Class<?>>();
        m.put("x", Integer.class);
        m.put("userId", String.class);
        m.put("element",Element.class);

        Jsontobean myBean  = (Jsontobean)JSONObject.toBean( JSONObject.fromObject(jsonStr), Jsontobean.class, m);
        System.out.println("x: " + myBean.getX());
        System.out.println("userId: " + myBean.getUserId());

        for(Element e : myBean.getElement()){
            System.out.println(e.getId() +"," + e.getName());
        }
    }

}

 

posted @ 2015-11-18 23:09  heyLuer  阅读(696)  评论(0编辑  收藏  举报