常用的java类型转json的转换类

公司不准引入json-lib-2.x.jar所以只好自己写了一个基本类型的object转json的类,然后支持8种基本类型和javabean,list,map,array,使用putJSON方法,key值随便写,value是要转换的对象。

JsonObjectConvert.java:
package com.pz.util;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class JsonObjectConvert {

    private StringBuffer sf = null;

    public  String SimpleObjectToJson(Object o){

        sf = new StringBuffer("{");

        //sf.append(o.getClass().getSimpleName());
        Field field[] = o.getClass().getDeclaredFields();
        String content = "";
        for(Field f : field ){
            try {
                f.setAccessible(true);
                content += "\"" + f.getName() + "\":\"" + convertNull(f.get(o)) +"\",";
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        sf.append(content);
        return sf.toString().substring(0, sf.length() - 1) + "}";
    }
    public Object convertNull(Object o){
        if(o == null){
            return "";
        }else {
            return o;
        }
    }
    @SuppressWarnings("unchecked")
    public  Object convertJSON(Object o){
        if(o == null){
            return "";
        }else if(o instanceof Boolean){
            return "\"" +o.toString() + "\"";
        }else if(o instanceof Character){
            return "\"" +o.toString() + "\"";
        }else if(o instanceof Short){
            return "\"" +o.toString() + "\"";
        }else if(o instanceof Integer){
            return "\"" +o.toString() + "\"";
        }else if(o instanceof Long){
            return "\"" +o.toString() + "\"";
        }else if(o instanceof Float){
            return "\"" +o.toString() + "\"";
        }else if(o instanceof Double){
            return "\"" +o.toString() + "\"";
        }else if(o instanceof Byte){
            return "\"" +o.toString() + "\"";
        }else if(o instanceof List){
            return listToJSON((List)o);
        }else if(o instanceof Map){
            return mapToJSON((Map)o);
        }else if(o.getClass().isArray()){
            return arrayToJSON(o);
        }else if(o instanceof String){
            return "\"" +o.toString() + "\"";
        }else if(o instanceof Date){
            return "\"" +o.toString() + "\"";
        }
        return SimpleObjectToJson(o);
    }
    @SuppressWarnings("unchecked")
    public  String listToJSON(List list){
        sf = new StringBuffer("[");
        for(int i = 0;i < list.size();i++){
            sf.append( convertJSON(list.get(i)) + ",");
        }
        return sf.toString().substring(0,sf.toString().length() - 1) + "]";
    }
    @SuppressWarnings("unchecked")
    public  String mapToJSON(Map map){
        sf = new StringBuffer("[");
        Iterator ite = map.entrySet().iterator();
        while(ite.hasNext()){
            Entry o = (Entry)ite.next();
            String key = convertJSON(o.getKey()).toString();
            sf.append("{\"" + key.substring(1, key.length() - 1) + "\":");
            sf.append(convertJSON(o.getValue()) +"},");
        }
        return sf.toString().substring(0,sf.toString().length() - 1) + "]";
    }
    public String arrayToJSON(Object o){
        sf = new StringBuffer("[");
        Object[] obj = (Object[])o;
        for(int i = 0;i < obj.length;i++){
            sf.append(convertJSON(obj[i]) + ",");
        }
        return sf.toString().substring(0, sf.toString().length() - 1) + "]";
    }
    //the sum method convert to json key --> value
    public static String putJSON(String key,Object value){
        JsonObjectConvert joc = new JsonObjectConvert();
        String jsonString = "{\"" + key + "\":" + joc.convertJSON(value) + "}";
        return jsonString;
    }
}

package com.pz.util;

import java.lang.reflect.Field;import java.util.Date;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;
public class JsonObjectConvert {private StringBuffer sf = null;public  String SimpleObjectToJson(Object o){sf = new StringBuffer("{");//sf.append(o.getClass().getSimpleName());Field field[] = o.getClass().getDeclaredFields();String content = "";for(Field f : field ){try {f.setAccessible(true);content += "\"" + f.getName() + "\":\"" + convertNull(f.get(o)) +"\",";} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}}sf.append(content);return sf.toString().substring(0, sf.length() - 1) + "}";}public Object convertNull(Object o){if(o == null){return "";}else {return o;}}@SuppressWarnings("unchecked")public  Object convertJSON(Object o){if(o == null){return "";}else if(o instanceof Boolean){return "\"" +o.toString() + "\"";}else if(o instanceof Character){return "\"" +o.toString() + "\"";}else if(o instanceof Short){return "\"" +o.toString() + "\"";}else if(o instanceof Integer){return "\"" +o.toString() + "\"";}else if(o instanceof Long){return "\"" +o.toString() + "\"";}else if(o instanceof Float){return "\"" +o.toString() + "\"";}else if(o instanceof Double){return "\"" +o.toString() + "\"";}else if(o instanceof Byte){return "\"" +o.toString() + "\"";}else if(o instanceof List){return listToJSON((List)o);}else if(o instanceof Map){return mapToJSON((Map)o);}else if(o.getClass().isArray()){return arrayToJSON(o);}else if(o instanceof String){return "\"" +o.toString() + "\"";}else if(o instanceof Date){return "\"" +o.toString() + "\"";}return SimpleObjectToJson(o);}@SuppressWarnings("unchecked")public  String listToJSON(List list){sf = new StringBuffer("[");for(int i = 0;i < list.size();i++){sf.append( convertJSON(list.get(i)) + ",");}return sf.toString().substring(0,sf.toString().length() - 1) + "]";}@SuppressWarnings("unchecked")public  String mapToJSON(Map map){sf = new StringBuffer("[");Iterator ite = map.entrySet().iterator();while(ite.hasNext()){Entry o = (Entry)ite.next();String key = convertJSON(o.getKey()).toString();sf.append("{\"" + key.substring(1, key.length() - 1) + "\":");sf.append(convertJSON(o.getValue()) +"},");}return sf.toString().substring(0,sf.toString().length() - 1) + "]";}public String arrayToJSON(Object o){sf = new StringBuffer("[");Object[] obj = (Object[])o;for(int i = 0;i < obj.length;i++){sf.append(convertJSON(obj[i]) + ",");}return sf.toString().substring(0, sf.toString().length() - 1) + "]";}//the sum method convert to json key --> valuepublic static String putJSON(String key,Object value){JsonObjectConvert joc = new JsonObjectConvert();String jsonString = "{\"" + key + "\":" + joc.convertJSON(value) + "}"; return jsonString;}}

时间: 2024-10-05 07:27:08

常用的java类型转json的转换类的相关文章

java 类型转json格式

json-lib-2.4-jdk15.jar List<People> mapPersonTypes = null; private JSONArray json_mapPersonTypes= JSONArray.fromObject(mapPersonTypes); 将的json_mapPersonTypes字符串内容拿出来放到软件中,就可以知道转换成功了! java 类型转json格式

java 字节流和字符流转换类InputStreamReader,OutPutStreamReader

import java.io.*; public class BufferDemo { public static void main(String[] args) throws IOException { BufferedReader buf=null; buf=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter a number:"); String str=buf

Java对象与JSON互相转换jsonlib以及手动创建JSON对象与数组——(二)

首先声明一下,jsonlib转换与GSON相比太差劲了,操作不是一般的繁琐.GSON可以直接转换成各种集合与对象类型.强烈推荐使用GSON.而且GSON一个方法就可以解决,jsonlib转来转去太繁琐了. 手动创建JSONObject与JSONArray有用,用于读取文件对字符串进行处理 -----------------------------jsonlib操作复杂,转换Map与list<map>更是复杂---------------- Jar包 User.java 1 package Te

【深入JAVA】将Json字符串转换成Map/List

在阅读的过程中有任何问题,欢迎一起交流 邮箱:[email protected] QQ:1494713801 Java代码 package jsonToMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /** * 说明 json字符串 转成 Map/List * @aut

Mybatis 中常用的java类型与jdbc类型

JDBC Type Java Type CHAR String VARCHAR String LONGVARCHAR String NUMERIC java.math.BigDecimal DECIMAL java.math.BigDecimal BIT boolean BOOLEAN boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT double DOUBLE double BINARY b

java对象与json串互转

1:java对象与json串转换: java对象—json串: JSONObject JSONStr = JSONObject.fromObject(object); String str = JSONStr.toString(); json串—java对象: JSONObject jsonObject = JSONObject.fromObject( jsonString ); Object pojo = JSONObject.toBean(jsonObject,pojoCalss); 2:j

json:JSONObject包的具体使用(JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包)

1.JSONObject介绍 JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包. 2.下载jar包 http://xiazai.jb51.net/201707/yuanma/lib_jb51.rar 提供了除JSONObject的jar之外依赖的其他6个jar包,一共7个jar文件 说明:因为工作中项目用到的版本是1.1的对应jdk1.3的版本,故本篇博客是基于1.1版本介绍的. 对应此版本的javadoc下载

Java 中常用的类:包括基本类型的包装类、Date 类、SimpleDateFormat 类、 Calendar 类、 Math 类

JAVA中的包装类 包装类里没有String,它是引用数据类型 基本类型是不能调用方法的,而其包装类具有很多方法 包装类主要提供了两大类方法: 1. 将本类型和其他基本类型进行转换的方法 2. 将字符串和本类型及包装类互相转换的方法 基本类型 对应的包装类 byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean Integer m=new Intege

Java中关于Json对象类型和字符串类型之间互相转化的问题

Java中关于Json格式转化Object,Map,Collection类型和String类型之间的转化在我们实际项目中应用的很是普遍和广泛.最近工作的过程中也是经常有,因此,自己封装了一个JsonUtil.java类. 所需要的jar包:slf4j-jdk14-1.5.6.jar,slf4j-api-1.5.6.jar------>此两个jar包是slf4j日志jar包 jackson-annotations-2.1.1.jar,jackson-core-2.1.1.jar,jackson-d