1. 程式人生 > >json轉換總結

json轉換總結

@requestMapping的produces和consumes屬性:

produces:它的作用是指定返回值型別,不但可以設定返回值型別還可以設定返回值的字元編碼;

consumes: 指定處理請求的提交內容型別(Content-Type),例如application/json, text/html;

 

前端請求json轉換成Bean物件報錯的解決:

@RequestMapping(value = "???", consumes = "application/json;charset=utf-8")

 

JSON.parseObject : 將Json字串轉化為相應的物件(

fastjson)

String jsonString = "{name:'Antony',age:'12',sex:'male',telephone:'88888'}";
Staff staff = JSON.parseObject(jsonString, Staff.class);
 

 

JSON.toJSONString : 將物件轉化為Json字串(fastjson)

String jsonStr = JSON.toJSONString(staff);

 

java 物件列表轉換為json物件陣列,並轉為字串(json-lib)

JSONArray array = JSONArray.fromObject(userlist);
String jsonstr = array.toString();

 

java物件轉換成json物件,並轉化為字串(json-lib)

JSONObject object = JSONObject.fromObject(invite);
String str=object.toString());

 

JSON字串轉換為JAVA 物件陣列(json-lib)

String personstr = getRequest().getParameter("persons");
JSONArray json = JSONArray.fromObject(personstr);
List<InvoidPerson> persons = (List<InvoidPerson>)JSONArray.toCollection(json, nvoidPerson.class);

 

JSON字串轉換為JAVA 物件(json-lib)

JSONObject jsonobject = JSONObject.fromObject(str);
PassportLendsEntity passportlends = null;
  try {
   //獲取一個json陣列
   JSONArray array = jsonobject.getJSONArray("passports");
   //將json陣列 轉換成 List<PassPortForLendsEntity>泛型
   List<PassPortForLendsEntity> list = new ArrayList<PassPortForLendsEntity>();
   for (int i = 0; i < array.size(); i++) {   
            JSONObject object = (JSONObject)array.get(i);  
            PassPortForLendsEntity passport = (PassPortForLendsEntity)JSONObject.toBean(object,
              PassPortForLendsEntity.class);
            if(passport != null){
             list.add(passport);
            }  
     }
   //轉換PassportLendsEntity 實體類
  passportlends = (PassportLendsEntity)JSONObject.toBean(jsonobject, PassportLendsEntity.class);

  str = "{\"lendperson\":\"李四\",\"lendcompany\":\"有限公司\",\"checkperson\":\"李四\",

  \"lenddate\":\"2010-07-19T00:00:00\",\"lendcounts\":4,\"
  passports\":[{\"passportid\":\"d\",\"name\":\"李豫川\",\"passporttype\":\"K\"},
  {\"passportid\":\"K9051\",\"name\":\"李平\",\"passporttype\":\"K\"},
  {\"passportid\":\"K90517\",\"name\":\"袁寒梅\",\"passporttype\":\"K\"},
  {\"passportid\":\"K905199\",\"name\":\"賀明\",\"passporttype\":\"K\"}]}";