json转map,json转bean

一个简单的工具类,把json对象转map,大家不要喷我...

在复杂的json对象中取值的时候大家肯定都很烦躁,为了解决这个问题,我们先把复杂的json转成简单的map,从map里面直接取值是不是舒服多了。

没有怎么测试,有同学用发现bug希望帮忙提意见

工具类

package xxx;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Slf4j
public class LinkUtil {

    /**
     * json转bean
     * bean属性上要标明链路
     *
     * @param json 元数据json
     * @param obj 接受封装结果的bean
     * @param bl 是否把元数据也放入map(如果bean需要封装则用true)
     */
    public static void json2Bean(Object obj,JSONObject json,boolean bl){
        //复杂json封装成map,链路作为key
        Map map = new HashMap<>();
        json2map(map,json,bl);
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            Link link = field.getAnnotation(Link.class);
            String addr = link.addr();
            if (StrUtil.isNotEmpty(addr)){
                Class type = field.getType();
                if(type.isPrimitive()){
                    log.info("{}不能是基础数据类型",field.getName());
                    continue;
                }
                Object o = map.get(addr);
                try {
                    field.set(obj,o);
                } catch (Exception e) {
                    log.error("{} 数据封装失败",addr,e);
                }
            }
        }
    }

    /**
     * 把json转map
     * key是链路
     * value是值
     *
     * @param map 接受封装结果的map
     * @param ob 元数据json
     * @param bl 是否把元数据也放入map
     */
    public static void json2map(Map map,Object ob,boolean bl) {
         json2map(map,"","root",ob,bl);
    }
    public static void json2map(Map map,String addr,String key,Object ob,boolean bl) {
        addr = StrUtil.isNotEmpty(addr)?addr+".":addr;
        if (ob instanceof JSONObject){
            JSONObject obj = (JSONObject) ob;
            if (bl){
                map.put(addr+key+"{}",obj);
            }
            Set keys = obj.keySet();
            for (String k:keys){
                Object o = obj.get(k);
                json2map(map,addr+key+"{}",k,o,bl);
            }
        }else if(ob instanceof JSONArray){
            JSONArray obj = (JSONArray) ob;
            if (bl){
                map.put(addr+key+"[]",obj);
            }
            for (int i = 0;i

注解类

package xxx;

import java.lang.annotation.*;

/**
 * 自定义注解,json对象中寻址
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Link {

    String addr() default "";

}

VO类

package xxx;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

@Data
public class LinkVo {

    @Link(addr = "root{}.code")
    Integer code;

    @Link(addr = "root{}.msg")
    String msg;

    @Link(addr = "root{}.dataJ{}")
    JSONObject dataJ;

    @Link(addr = "root{}.dataA[]")
    JSONArray dataA;
}

测试类

package xxx;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LinkDemo {

    public static void main(String[] args) {
//        json2bean();
        json2map();
    }

    public static void json2bean() {
        JSONObject obj = JSONObject.parseObject(str);
        LinkVo vo = new LinkVo();
        LinkUtil.json2Bean(vo, obj, false);

        System.out.println(vo.getCode());
        System.out.println(vo.getDataJ());
        System.out.println(vo.getDataA());
    }

    public static void json2map() {
        JSONObject obj = JSONObject.parseObject(str);
        Map map = new HashMap<>();
        LinkUtil.json2map(map, obj, true);

        System.out.println(map);
        System.out.println(map.get("root{}.code"));
        System.out.println(map.get("root{}.dataJ{}"));
        System.out.println(map.get("root{}.dataJ{}.dataj1"));
    }

    static String str = "{\n" +
            "\"code\": 1000,\n" +
            "\"msg\": \"成功\",\n" +
            "\"dataJ\": {\n" +
            "\"dataj1\": \"dataj1\",\n" +
            "\"dataj2\": \"dataj2\"\n" +
            "},\n" +
            "\"dataA\": [{\n" +
            "\"dataa1\": \"dataa1\"\n" +
            "}, {\n" +
            "\"dataa2\": \"dataa2\"\n" +
            "}]\n" +
            "}";

//不带元数据的map
/*{
    root{}.code=1000,
    root{}.msg=成功,
    root{}.dataJ{}.dataj1=dataj1,
    root{}.dataJ{}.dataj2=dataj2,
    root{}.dataA[].0{}.dataa1=dataa1,
    root{}.dataA[].1{}.dataa2=dataa2,
}*/

//带元数据的map
/*{
    root{}={"msg":"成功","code":1000,"dataA":[{"dataa1":"dataa1"},{"dataa2":"dataa2"}],"dataJ":{"dataj1":"dataj1","dataj2":"dataj2"}},
    root{}.code=1000,
    root{}.msg=成功,
    root{}.dataJ{}={"dataj1":"dataj1","dataj2":"dataj2"},
    root{}.dataJ{}.dataj1=dataj1,
    root{}.dataJ{}.dataj2=dataj2,
    root{}.dataA[]=[{"dataa1":"dataa1"},{"dataa2":"dataa2"}],
    root{}.dataA[].0{}={"dataa1":"dataa1"},
    root{}.dataA[].0{}.dataa1=dataa1,
    root{}.dataA[].1{}={"dataa2":"dataa2"},
    root{}.dataA[].1{}.dataa2=dataa2,
}*/
}

你可能感兴趣的:(json,java,开发语言)