JSON 字串 與 java 對象的轉換

來源:互聯網
上載者:User
jsonLib 經典文章:http://json-lib.sourceforge.net/xref-test/net/sf/json/TestJSONObject.html

// 引入相應的包

//json-lib-2.2-jdk15.jar

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

1. //把java 對象列錶轉換為json對象數組,並轉為字串

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

2.//把java對象轉換成json對象,並轉化為字串

  JSONObject object = JSONObject.fromObject(invite);
  Log4jInit.ysulogger.debug(object.toString());

3.//把JSON字串轉換為JAVA 對象數組

  String personstr = getRequest().getParameter("persons");
  JSONArray json = JSONArray.fromObject(personstr);
  List<InvoidPerson> persons = (List<InvoidPerson>)JSONArray.toCollection(json, nvoidPerson.class);
4.//把JSON字串轉換為JAVA 對象

  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\"}]}";
   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);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.