json解析工具解决new Gson().toJson() 将存在JSONObject成员的对象转json字符串有map字段

json是开发过程中非常常用的数据交互格式
实际项目过程中经常会需要将一个对象转换成json字符串,常用 new Gson().toJson 转换方法,如下

public class Test {
    static class Student {
        public String name;
        public long no;

        public Student(String name, long no) {
            this.name = name;
            this.no = no;
        }
    }

    public static void main(String[] args) {
        String s1 = new Gson().toJson(new Student("zhangsan", 110));
        System.out.println(s1);
    }
}
控制台输出:{"name":"zhangsan","no":110}

上述将一个普通对象转换成json字符串是正常的,但是如果要转换json字符的对象中存在JSONObecjt成员,new Gson().toJson转换后的会存在 map 字段,如下:

public class Test {
    static class Student{
        public String name;
        public long no;
        public JSONObject data;
        public Student(String name,long no,JSONObject data){
            this.name = name;
            this.no = no;
            this.data = data;
        }
    }

    public static void main(String[] args){
        JSONObject data = new JSONObject();
        data.put("text","你好");

        String s = new Gson().toJson(new Student("zhangsan",110,data));
        System.out.println(s);
    }
}

控制台输出结果:

{"name":"zhangsan","no":110,"data":{"map":{"text":"你好"}}}

如果想要去掉上述map字段,可以尝试使用我下面提供的json工具,源码 如下:
JSONUtil

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import org.json.JSONObject;

public class JSONUtil {

	public static String encodeJSONString(Object bean) {
		return encodeJSON(bean).toString();
	}

	public static JSONObject encodeJSON(Object bean) {
		JSONObject json = new JSONObject();
		Class<?> clazz = bean.getClass();
		do {
			Field[] fileds = clazz.getDeclaredFields();
			for (Field field : fileds) {
				try {
					if (Modifier.isStatic(field.getModifiers())) {
                        continue;
                    }

					String fieldName = field.getName();
					field.setAccessible(true);
					Object value = field.get(bean);

					json.put(fieldName, value);

				} catch (Exception e) {
				}
			}
		} while (!(clazz = clazz.getSuperclass()).equals(Object.class));
		return json;
	}

	public static <T> T decodeJSON(JSONObject json, Class<T> clazz) {

		T t = null;
		try {
			t = (T) clazz.newInstance();
			Field[] fileds = clazz.getDeclaredFields();
			for (Field field : fileds) {
				try {
					String fieldName = field.getName();
					if (Modifier.isStatic(field.getModifiers())) {
						continue;
					}
					Object value = json.get(fieldName);

					if (value != null) {
						String temp = value.toString();
						Class<?> type = field.getType();

						if ("boolean".equals(type.getName())) {
							boolean b = Boolean.parseBoolean(temp);
							field.setAccessible(true);
							field.set(t, b);
						} else if ("float".equals(type.getName())) {
							float b = Float.parseFloat(temp);
							field.setAccessible(true);
							field.set(t, b);
						} else if ("long".equals(type.getName())) {
							long b = Long.parseLong(temp);
							field.setAccessible(true);
							field.set(t, b);
						} else if ("double".equals(type.getName())) {
							double b = Double.parseDouble(temp);
							field.setAccessible(true);
							field.set(t, b);
						} else if ("int".equals(type.getName())) {
							int b = Integer.parseInt(temp);
							field.setAccessible(true);
							field.set(t, b);
						} else if ("byte".equals(type.getName())) {
							Byte b = Byte.parseByte(temp);
							field.setAccessible(true);
							field.set(t, b);
						} else if ("short".equals(type.getName())) {
							short b = Short.parseShort(temp);
							field.setAccessible(true);
							field.set(t, b);
						} else {
							Constructor<?> constructor = type.getDeclaredConstructor(String.class);
							Object object = constructor.newInstance(temp);
							field.setAccessible(true);
							field.set(t, object);
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return t;
	}

}

使用JSONUtil 再来一次,如下:

public class Test {
    static class Student {
        public String name;
        public long no;
        public JSONObject data;

        public Student(String name, long no, JSONObject data) {
            this.name = name;
            this.no = no;
            this.data = data;
        }
    }

    public static void main(String[] args) {
        JSONObject data = new JSONObject();
        data.put("text", "你好");

        String s = JSONUtil.encodeJSONString(new Student("zhangsan", 110, data));
        System.out.println(s);
    }
}

输出结果:

{"no":110,"data":{"text":"你好"},"name":"zhangsan"}

map字段没有了,问题解决!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值