当前位置: 代码迷 >> JavaScript >> 提取对象属性值变换为json格式的数据[转]
  详细解决方案

提取对象属性值变换为json格式的数据[转]

热度:351   发布时间:2012-08-07 14:54:49.0
提取对象属性值转换为json格式的数据[转]
Java代码 
import java.lang.reflect.Field;  
import java.util.Collection;  
import java.util.Iterator;  
/* 
* 将pojo对象的属性值提取出来,组成json格式的数据 
* 当前版本只能对最基本的pojo对象进行转化,类似于下面的格式: 
      public class Pojo { 
        private String name; 
        private int age; 
    public int getAge() {   
        return age;   
      }   
        
      public String getName() {   
        return name;   
      }   
        
      public void setAge(int age) {   
        this.age = age;   
      }   
        
      public void setName(String name) {   
        this.name = name;   
      }   
         
    } 
* 单个对象返回{'name':age}格式;集合对象返回{'name':age},{'name':age}... 
*  
* author:scriptguy 
* date:  2010/04/06 
*/ 
public class JsonUtil {  
      
    /* 
    ** 暴露出来的方法,传入需要将属性值转换为json数据格式的pojo 
    ** 会抛出IllegalAccessException异常,需要捕捉 
    */ 
    public static String toJson(Object obj) throws IllegalAccessException{  
        Class cla = obj.getClass();  
        Field[] fields = cla.getDeclaredFields();  
        String[] names = fieldToNames(fields);  
        Object[] values = fieldToValues(fields,obj);  
        String json = produceToJson(names,values);  
        return json;  
    }  
      
    private static String[] fieldToNames(Field[] fields) {  
        String[] names = new String[fields.length];  
        for(int i = 0;i < fields.length;i++) {  
            fields[i].setAccessible(true);//将此对象的 accessible 标志设置为可以读取  
            names[i] = fields[i].getName();  
        }  
        return names;  
    }  
      
    private static Object[] fieldToValues(Field[] fields,Object obj) throws IllegalAccessException{  
        Object[] values = new Object[fields.length];  
        for(int i = 0;i < fields.length;i++) {  
            values[i] = fields[i].get(obj);  
        }  
          
        return values;  
    }  
      
    private static String produceToJson(String[] names,Object[] values) {  
        if(names.length != values.length) {  
            new RuntimeException("转化json数据出错!!!");        
        }  
        StringBuilder json = new StringBuilder();  
        json.append("{");  
        for(int i = 0;i < names.length;i++) {  
            json.append("'");  
            json.append(names[i]);  
            json.append("':");  
            processFieldValue(values[i],json);  
            if(i < names.length - 1) {  
                json.append(",");  
            }  
        }  
        json.append("}");  
        return json.toString();  
    }  
      
    private static void processFieldValue(Object obj,StringBuilder json) {  
        if(obj instanceof Number) {  
            json.append(obj);  
        } else {  
        json.append("'");  
        json.append(obj);  
        json.append("'");  
        }  
    }  
      
    public static String allToJson(Collection coll) throws IllegalAccessException{  
        Iterator iterator = coll.iterator();  
        StringBuilder json = new StringBuilder();  
        Object obj;  
        while(iterator.hasNext()) {  
            obj = iterator.next();  
            json.append(toJson(obj));  
            json.append(",");  
        }  
        int delete = json.lastIndexOf(",");  
        json = json.deleteCharAt(delete);  
        return json.toString();  
    }  
      
      
    /* 
    ** 
    */ 


import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Iterator;
/*
* 将pojo对象的属性值提取出来,组成json格式的数据
* 当前版本只能对最基本的pojo对象进行转化,类似于下面的格式:
  public class Pojo {
private String name;
private int age;
    public int getAge() { 
  return age; 
  } 
  
  public String getName() { 
  return name; 
  } 
  
  public void setAge(int age) { 
  this.age = age; 
  } 
  
  public void setName(String name) { 
  this.name = name; 
  } 

}
* 单个对象返回{'name':age}格式;集合对象返回{'name':age},{'name':age}...
*
* author:scriptguy
* date:  2010/04/06
*/
public class JsonUtil {

/*
** 暴露出来的方法,传入需要将属性值转换为json数据格式的pojo
** 会抛出IllegalAccessException异常,需要捕捉
*/
public static String toJson(Object obj) throws IllegalAccessException{
Class cla = obj.getClass();
Field[] fields = cla.getDeclaredFields();
String[] names = fieldToNames(fields);
Object[] values = fieldToValues(fields,obj);
String json = produceToJson(names,values);
return json;
}

private static String[] fieldToNames(Field[] fields) {
String[] names = new String[fields.length];
for(int i = 0;i < fields.length;i++) {
fields[i].setAccessible(true);//将此对象的 accessible 标志设置为可以读取
names[i] = fields[i].getName();
}
return names;
}

private static Object[] fieldToValues(Field[] fields,Object obj) throws IllegalAccessException{
Object[] values = new Object[fields.length];
for(int i = 0;i < fields.length;i++) {
values[i] = fields[i].get(obj);
}

return values;
}

private static String produceToJson(String[] names,Object[] values) {
if(names.length != values.length) {
new RuntimeException("转化json数据出错!!!");
}
StringBuilder json = new StringBuilder();
json.append("{");
for(int i = 0;i < names.length;i++) {
json.append("'");
json.append(names[i]);
json.append("':");
processFieldValue(values[i],json);
if(i < names.length - 1) {
json.append(",");
}
}
json.append("}");
return json.toString();
}

private static void processFieldValue(Object obj,StringBuilder json) {
if(obj instanceof Number) {
json.append(obj);
} else {
json.append("'");
json.append(obj);
json.append("'");
}
}

public static String allToJson(Collection coll) throws IllegalAccessException{
Iterator iterator = coll.iterator();
StringBuilder json = new StringBuilder();
Object obj;
while(iterator.hasNext()) {
obj = iterator.next();
json.append(toJson(obj));
json.append(",");
}
int delete = json.lastIndexOf(",");
json = json.deleteCharAt(delete);
return json.toString();
}


/*
**
*/
}


测试代码:
Java代码 
import java.util.Collection;  
import java.util.*;  
public class TestJsonUtil {  
    public static void main(String[] args) throws Exception{  
        Pojo pojo1 = new Pojo("list",23);  
        Pojo pojo = new Pojo("scriptguy",22);  
        List<Object> lista = new ArrayList<Object>();  
        lista.add(pojo1);  
        lista.add(pojo);  
        System.out.println(JsonUtil.allToJson(lista));  
    }  
 


import java.util.Collection;
import java.util.*;
public class TestJsonUtil {
public static void main(String[] args) throws Exception{
Pojo pojo1 = new Pojo("list",23);
Pojo pojo = new Pojo("scriptguy",22);
List<Object> lista = new ArrayList<Object>();
lista.add(pojo1);
lista.add(pojo);
System.out.println(JsonUtil.allToJson(lista));
}

}


结果:
      {'name':'list','age':23},{'name':'scriptguy','age':22}

-------------------------

前面我有用到android发送json数据;这里我想总结一下我用到的解析json数据格式的方式

json数据格式解析我自己分为两种;

一种是普通的,一种是带有数组形式的;




普通形式的:
服务器端返回的json数据格式如下:

{"userbean":{"Uid":"100196","Showname":"\u75af\u72c2\u7684\u7334\u5b50","Avtar":null,"State":1}}

分析代码如下:

// TODO 状态处理 500 200
                int res = 0;
                res = httpClient.execute(httpPost).getStatusLine().getStatusCode();
                if (res == 200) {
                    /*
                     * 当返回码为200时,做处理
                     * 得到服务器端返回json数据,并做处理
                     * */
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    StringBuilder builder = new StringBuilder();
                    BufferedReader bufferedReader2 = new BufferedReader(
                            new InputStreamReader(httpResponse.getEntity().getContent()));
                    String str2 = "";
                    for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2
                            .readLine()) {
                        builder.append(s);
                    }
                    Log.i("cat", ">>>>>>" + builder.toString());

JSONObject jsonObject = new JSONObject(builder.toString())
                        .getJSONObject("userbean");

                String Uid;
                String Showname;
                String Avtar;
                String State;

                Uid = jsonObject.getString("Uid");
                Showname = jsonObject.getString("Showname");
                Avtar = jsonObject.getString("Avtar");
                State = jsonObject.getString("State");
带数组形式的:
服务器端返回的数据格式为:

{"calendar":
    {"calendarlist":
            [
            {"calendar_id":"1705","title":"(\u4eb2\u5b50)ddssd","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288927800","endshowtime":"1288931400","allDay":false},
            {"calendar_id":"1706","title":"(\u65c5\u884c)","category_name":"\u9ed8\u8ba4\u5206\u7c7b","showtime":"1288933200","endshowtime":"1288936800","allDay":false}
            ]
    }
}

分析代码如下:

// TODO 状态处理 500 200
                int res = 0;
                res = httpClient.execute(httpPost).getStatusLine().getStatusCode();
                if (res == 200) {
                    /*
                     * 当返回码为200时,做处理
                     * 得到服务器端返回json数据,并做处理
                     * */
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    StringBuilder builder = new StringBuilder();
                    BufferedReader bufferedReader2 = new BufferedReader(
                            new InputStreamReader(httpResponse.getEntity().getContent()));
                    String str2 = "";
                    for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2
                            .readLine()) {
                        builder.append(s);
                    }
                    Log.i("cat", ">>>>>>" + builder.toString());
                    /**
                     * 这里需要分析服务器回传的json格式数据,
                     */
                    JSONObject jsonObject = new JSONObject(builder.toString())
                            .getJSONObject("calendar");
                    JSONArray jsonArray = jsonObject.getJSONArray("calendarlist");
                    for(int i=0;i<jsonArray.length();i++){
                        JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i);
                        CalendarInfo calendarInfo = new CalendarInfo();
                        calendarInfo.setCalendar_id(jsonObject2.getString("calendar_id"));
                        calendarInfo.setTitle(jsonObject2.getString("title"));
                        calendarInfo.setCategory_name(jsonObject2.getString("category_name"));
                        calendarInfo.setShowtime(jsonObject2.getString("showtime"));
                        calendarInfo.setEndtime(jsonObject2.getString("endshowtime"));
                        calendarInfo.setAllDay(jsonObject2.getBoolean("allDay"));
                        calendarInfos.add(calendarInfo);
                    }

总结,普通形式的只需用JSONObject ,带数组形式的需要使用JSONArray 将其变成一个list。


  相关解决方案