«

java中List对象转换为JSON对象

时间:2024-3-2 19:32     作者:韩俊     分类: Android


java中List对象转换为JSON对象

分类:
Java知识 2011-11-22 14:12
16462人阅读 评论(7)
收藏
举报
jsonlistjavastringobjecthashmap

java中List对象转换为JSON对象

以为兄弟写的!感觉风格颇为幽默,自恋的来说,很像我的风格哦!呵呵!

好啦!帮他的成果复制过来吧!

一、什么是JSON

  JSON 即 JavaScript Object Natation(Java对象表示法),它是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互。

  简而言之,JSON就是JavaScript交换数据的一种格式。例子如下:

<span style="color:#ff0000;FONT-SIZE: 16px"><strong>{"username":"coolcooldool","password":"1230","usertype":"superadmin"}</strong></span>
<span style="color:#ff0000;FONT-SIZE: 16px"><strong>{"list":[{"password":"1230","username":"coolcooldool"},{"password":"thisis2","username":"okokok"}]}</strong></span>
<span style="color:#274e13;FONT-SIZE: 16px">第二种是有数组的情况,我也不用文字表述JSON到底是怎么构成的了,相信长眼睛的人都看懂了,哇咔咔!~</span>
<span style="font-size:24px;color:#ff00ff;"><strong>二、为什么使用JSON而不是XML</strong></span>
  他们都是这样说的:
  <span style="color:#0000ff;FONT-SIZE: 13px"><em>尽管有许多宣传关于 XML 如何拥有跨平台,跨语言的优势,然而,除非应用于 Web Services,否则,在普通的 Web 应用中,开发者经常为 XML 的解析伤透了脑筋,无论是服务器端生成或处理 XML,还是客户端用 JavaScript 解析 XML,都常常导致复杂的代码,极低的开发效率。实际上,对于大多数 Web 应用来说,他们根本不需要复杂的 XML 来传输数据,XML 的扩展性很少具有优势,许多 AJAX 应用甚至直接返回 HTML 片段来构建动态 Web 页面。和返回 XML 并解析它相比,返回 HTML 片段大大降低了系统的复杂性,但同时缺少了一定的灵活性。</em></span>
  <span style="color:#ff0000;"><span style="color:#000000;">我认为就是说:</span><strong>解析XML太费劲了。</strong></span>
<span style="font-size:24px;color:#ff00ff;"><strong>三、如何使用</strong></span>
<span style="color:#274e13;FONT-SIZE: 16px"><span style="color:#000000;">  </span>当然最直接的方法就是,你自己写一个类,把你在数据库中查到的list转换成Sting,格式就是JSON样子的就行,但前提是你比较牛叉,能很快写出来,并且是对的,对于我这么不牛叉的人来说,我选第二种方法。</span>
<span style="color:#274e13;FONT-SIZE: 16px">  去网上找别人写好的类,看一遍,拿过来用就好了。我目前找到了两个类,都能达到效果,待我慢慢道来。</span>
  1.在你的MyEclipse里新建一个Web Project,就叫<strong><span style="color:#ff0000;">Ajax_Json</span></strong>吧。
  2.新建一个类,名字叫做<span style="color:#ff0000;"><strong>JsonUtil.java</strong></span>,打包到<strong><span style="color:#ff0000;">young.ajax.json</span></strong>,把下面代码复制进去。

[java]
view plaincopyprint?

package young.ajax.json; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class JsonUtil { private static Log log = LogFactory.getLog(JsonUtil.class); public static String object2json(Object obj) { StringBuilder json = new StringBuilder(); if (obj == null) { json.append(""""); } else if (obj instanceof String || obj instanceof Integer || obj instanceof Float || obj instanceof Boolean || obj instanceof Short || obj instanceof Double || obj instanceof Long || obj instanceof BigDecimal || obj instanceof BigInteger || obj instanceof Byte) { json.append(""").append(string2json(obj.toString())).append("""); } else if (obj instanceof Object[]) { json.append(array2json((Object[]) obj)); } else if (obj instanceof List) { json.append(list2json((List<?>) obj)); } else if (obj instanceof Map) { json.append(map2json((Map<?, ?>) obj)); } else if (obj instanceof Set) { json.append(set2json((Set<?>) obj)); } else { json.append(bean2json(obj)); } return json.toString(); } public static String bean2json(Object bean) { StringBuilder json = new StringBuilder(); json.append("{"); PropertyDescriptor[] props = null; try { props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors(); } catch (IntrospectionException e) {} if (props != null) { for (int i = 0; i < props.length; i++) { try { String name = object2json(props[i].getName()); String value = object2json(props[i].getReadMethod().invoke(bean)); json.append(name); json.append(":"); json.append(value); json.append(","); } catch (Exception e) {} } json.setCharAt(json.length() - 1, '}'); } else { json.append("}"); } return json.toString(); } public static String list2json(List<?> list) { StringBuilder json = new StringBuilder(); json.append("["); if (list != null && list.size() > 0) { for (Object obj : list) { json.append(object2json(obj)); json.append(","); } json.setCharAt(json.length() - 1, ']'); } else { json.append("]"); } return json.toString(); } public static String array2json(Object[] array) { StringBuilder json = new StringBuilder(); json.append("["); if (array != null && array.length > 0) { for (Object obj : array) { json.append(object2json(obj)); json.append(","); } json.setCharAt(json.length() - 1, ']'); } else { json.append("]"); } return json.toString(); } public static String map2json(Map<?, ?> map) { StringBuilder json = new StringBuilder(); json.append("{"); if (map != null && map.size() > 0) { for (Object key : map.keySet()) { json.append(object2json(key)); json.append(":"); json.append(object2json(map.get(key))); json.append(","); } json.setCharAt(json.length() - 1, '}'); } else { json.append("}"); } return json.toString(); } public static String set2json(Set<?> set) { StringBuilder json = new StringBuilder(); json.append("["); if (set != null && set.size() > 0) { for (Object obj : set) { json.append(object2json(obj)); json.append(","); } json.setCharAt(json.length() - 1, ']'); } else { json.append("]"); } return json.toString(); } public static String string2json(String s) { if (s == null) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); switch (ch) { case '"': sb.append("\""); break; case '\': sb.append("\"); break; case 'b': sb.append("\b"); break; case 'f': sb.append("\f"); break; case 'n': sb.append("\n"); break; case 'r': sb.append("\r"); break; case 't': sb.append("\t"); break; case '/': sb.append("\/"); break; default: if (ch >= 'u0000' && ch <= 'u001F') { String ss = Integer.toHexString(ch); sb.append("\u"); for (int k = 0; k < 4 - ss.length(); k++) { sb.append('0'); } sb.append(ss.toUpperCase()); } else { sb.append(ch); } } } return sb.toString(); } }

package young.ajax.json;

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JsonUtil {
private static Log log = LogFactory.getLog(JsonUtil.class);
public static String object2json(Object obj) {
             StringBuilder json = new StringBuilder();
             if (obj == null) {
               json.append("""");
             } else if (obj instanceof String || obj instanceof Integer || obj instanceof Float
                 || obj instanceof Boolean || obj instanceof Short || obj instanceof Double
                 || obj instanceof Long || obj instanceof BigDecimal || obj instanceof BigInteger
                 || obj instanceof Byte) {
               json.append(""").append(string2json(obj.toString())).append(""");
             } else if (obj instanceof Object[]) {
               json.append(array2json((Object[]) obj));
             } else if (obj instanceof List) {
               json.append(list2json((List<?>) obj));
             } else if (obj instanceof Map) {
               json.append(map2json((Map<?, ?>) obj));
             } else if (obj instanceof Set) {
               json.append(set2json((Set<?>) obj));
             } else {
               json.append(bean2json(obj));
             }
             return json.toString();
  }
public static String bean2json(Object bean) {
             StringBuilder json = new StringBuilder();
             json.append("{");
             PropertyDescriptor[] props = null;
             try {
               props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();
             } catch (IntrospectionException e) {}
             if (props != null) {
               for (int i = 0; i < props.length; i++) {
                 try {
                   String name = object2json(props[i].getName());
                   String value = object2json(props[i].getReadMethod().invoke(bean));
                   json.append(name);
                   json.append(":");
                   json.append(value);
                   json.append(",");
                 } catch (Exception e) {}
               }
               json.setCharAt(json.length() - 1, '}');
             } else {
               json.append("}");
             }
             return json.toString();
  }
public static String list2json(List<?> list) {
             StringBuilder json = new StringBuilder();
             json.append("[");
             if (list != null && list.size() > 0) {
               for (Object obj : list) {
                 json.append(object2json(obj));
                 json.append(",");
               }
               json.setCharAt(json.length() - 1, ']');
             } else {
               json.append("]");
             }
             return json.toString();
  }
public static String array2json(Object[] array) {
             StringBuilder json = new StringBuilder();
             json.append("[");
             if (array != null && array.length > 0) {
               for (Object obj : array) {
                 json.append(object2json(obj));
                 json.append(",");
               }
               json.setCharAt(json.length() - 1, ']');
             } else {
               json.append("]");
             }
             return json.toString();
  }
public static String map2json(Map<?, ?> map) {
             StringBuilder json = new StringBuilder();
             json.append("{");
             if (map != null && map.size() > 0) {
               for (Object key : map.keySet()) {
                 json.append(object2json(key));
                 json.append(":");
                 json.append(object2json(map.get(key)));
                 json.append(",");
               }
               json.setCharAt(json.length() - 1, '}');
             } else {
               json.append("}");
             }
             return json.toString();
  }
public static String set2json(Set<?> set) {
             StringBuilder json = new StringBuilder();
             json.append("[");
             if (set != null && set.size() > 0) {
               for (Object obj : set) {
                 json.append(object2json(obj));
                 json.append(",");
               }
               json.setCharAt(json.length() - 1, ']');
             } else {
               json.append("]");
             }
             return json.toString();
  }
public static String string2json(String s) {
             if (s == null)
               return "";
             StringBuilder sb = new StringBuilder();
             for (int i = 0; i < s.length(); i++) {
               char ch = s.charAt(i);
               switch (ch) {
               case '"':
                 sb.append("\"");
                 break;
               case '\':
                 sb.append("\\");
                 break;
               case 'b':
                 sb.append("\b");
                 break;
               case 'f':
                 sb.append("\f");
                 break;
               case 'n':
                 sb.append("\n");
                 break;
               case 'r':
                 sb.append("\r");
                 break;
               case 't':
                 sb.append("\t");
                 break;
               case '/':
                 sb.append("\/");
                 break;
               default:
                 if (ch >= 'u0000' && ch <= 'u001F') {
                   String ss = Integer.toHexString(ch);
                   sb.append("\u");
                   for (int k = 0; k < 4 - ss.length(); k++) {
                     sb.append('0');
                   }
                   sb.append(ss.toUpperCase());
                 } else {
                   sb.append(ch);
                 }
               }
             }
             return sb.toString();
  }
}

这应该是一个高手自己写的代码,就是用刚才第一种方法的人,哈哈!这个类就能将你的几乎所有类型转换成JSON形式的字符串,你可以自己写个类测试一下,我就不写了。
<span style="color:#0000ff;">呐,到现在为止,我们已经有一种方法能将list型的东东转换成为JSON形式的数据了。但是,偷偷的告诉你,还有一种方法,其实效果是一样的,但是传说是官方的,所以用了会显得比较专业,比较牛叉所以我选了第二种,哇咔咔!</span>
[java] view plaincopyprint? package young.ajax.json;import
package young.ajax.json;import 
[java] view plaincopyprint? java.util.HashMap;
java.util.HashMap;
[java] view plaincopyprint? import java.util.List;
import java.util.List;
[java] view plaincopyprint? import java.util.Map;
import java.util.Map;
[java] view plaincopyprint? import net.sf.json.JSONArray;
import net.sf.json.JSONArray;
[java] view plaincopyprint? import net.sf.json.JSONException;
import net.sf.json.JSONException;
[java] view plaincopyprint? import net.sf.json.JSONObject;
import net.sf.json.JSONObject;
[java] view plaincopyprint? public class JsonConvert
public class JsonConvert 
[java] view plaincopyprint? { public static JSONObject message(String message, boolean success)
   { public static JSONObject message(String message, boolean success) 
[java] view plaincopyprint? { Map map = new HashMap();
   {          Map map = new HashMap();         
[java] view plaincopyprint? map.put("success", success);
        map.put("success", success);         
[java] view plaincopyprint? map.put("message", message);
        map.put("message", message);         
[java] view plaincopyprint? return JSONObject.fromObject(map);
        return JSONObject.fromObject(map); 
[java] view plaincopyprint? }
   }
[java] view plaincopyprint? public static JSONObject generate(List list)
   public static JSONObject generate(List list) 
[java] view plaincopyprint? { Map map = new HashMap();
   {          Map map = new HashMap();        
[java] view plaincopyprint? map.put("totalProperty", list.size());
       map.put("totalProperty", list.size());        
[java] view plaincopyprint? map.put("root", list);
       map.put("root", list);          
[java] view plaincopyprint? return JSONObject.fromObject(map);
       return JSONObject.fromObject(map); 
[java] view plaincopyprint? }
   }
[java] view plaincopyprint? public static JSONObject javabean2json(Object object, String message, boolean success)
   public static JSONObject javabean2json(Object object, String message, boolean success)
[java] view plaincopyprint? { Map map = new HashMap();
    {          Map map = new HashMap();         
[java] view plaincopyprint? map.put("success", success);
        map.put("success", success);         
[java] view plaincopyprint? map.put("message", message);
        map.put("message", message);         
[java] view plaincopyprint? map.put("data", object);
        map.put("data", object);        
[java] view plaincopyprint? return JSONObject.fromObject(map);
         return JSONObject.fromObject(map);
[java] view plaincopyprint? }
    }
[java] view plaincopyprint? public static JSONObject objectcollect2json(List list, String total) {
   public static JSONObject objectcollect2json(List list, String total) {         
[java] view plaincopyprint? Map map = new HashMap();
    Map map = new HashMap();          
[java] view plaincopyprint? map.put("totalProperty", total);
   map.put("totalProperty", total);         
[java] view plaincopyprint? map.put("root", list);
    map.put("root", list);         
[java] view plaincopyprint? return JSONObject.fromObject(map);
    return JSONObject.fromObject(map); 
[java] view plaincopyprint? }
   }
[java] view plaincopyprint? public static JSONArray getJSONArrayFormString(String str) {
   public static JSONArray getJSONArrayFormString(String str) {          
[java] view plaincopyprint? if (str == null || str.trim().length() == 0) {
   if (str == null || str.trim().length() == 0) {         
[java] view plaincopyprint? return null;
     return null;          
[java] view plaincopyprint? }
   }          
[java] view plaincopyprint? JSONArray jsonArray = null;
   JSONArray jsonArray = null;         
[java] view plaincopyprint? try {
    try {          
[java] view plaincopyprint? jsonArray = JSONArray.fromObject(str);
    jsonArray = JSONArray.fromObject(str);         
[java] view plaincopyprint? } catch (JSONException e) { e.printStackTrace(); }
    } catch (JSONException e) {           e.printStackTrace();          }        
[java] view plaincopyprint? return jsonArray; }
     return jsonArray; }
[java] view plaincopyprint? public static JSONObject StringToJSONOBject(String str) {
   public static JSONObject StringToJSONOBject(String str) {      
[java] view plaincopyprint? if (str == null || str.trim().length() == 0)
       if (str == null || str.trim().length() == 0)
[java] view plaincopyprint? { return null; }
    {           return null;          }         
[java] view plaincopyprint? JSONObject jsonObject = null;
    JSONObject jsonObject = null;         
[java] view plaincopyprint? try { jsonObject = JSONObject.fromObject(str);
    try {           jsonObject = JSONObject.fromObject(str);       
[java] view plaincopyprint? } catch (JSONException e) { e.printStackTrace(); }
      } catch (JSONException e) {           e.printStackTrace();          }        
[java] view plaincopyprint? return jsonObject; }}
     return jsonObject; }}

  3.新建一个Java类,名字叫做<strong><span style="color:#ff0000;">JsonConvert.java</span></strong>,同样打包到<span style="color:#ff0000;"><strong>young.ajax.json</strong></span>,将下面代码粘到里面。
 
<span style="color:#0000ff;">怎么样,这个看着更专业吧,但是你现在发现了,有好多的可修正的红叉叉啊,为什么哩?难道是类库?Bingo!需要好一大堆包啊。。哎!我观察了一下,我的里面有这么多包包,不排除有没用上的哈。</span>

标签: android

热门推荐