java 对象与json互转

有时为了项目需求,会将对象数据转换成json数据,以下是个人根据项目需求实现的方法。

项目中需要将数据格式:

[{
    "node": "0",
    "index": null,
    "status": null,
    "preNode": null,
    "postNode": [{
        "node": "xxx_4"
    },
    {
        "node": "xxx_3"
    },
    {
        "node": "xxx_2"
    },
    {
        "node": "xxx_14"
    }]
},
{
    "node": "xxx_2",
    "index": "index_1",
    "status": "表达式1",
    "preNode": [{
        "node": "xxx_0"
    }],
    "postNode": [{
        "node": "xxx_5"
    }]
},
{
    "node": "xxx_14",
    "index": "index_4",
    "status": "表达式5",
    "preNode": [{
        "node": "xxx_0"
    }],
    "postNode": [{
        "node": "xxx_13"
    },
    {
        "node": "xxx_5"
    }]
},
{
    "node": "xxx_3",
    "index": "index_2",
    "status": "表达式2",
    "preNode": [{
        "node": "xxx_0"
    }],
    "postNode": [{
        "node": "xxx_5"
    }]
},
{
    "node": "xxx_4",
    "index": "index_3",
    "status": "表达式3",
    "preNode": [{
        "node": "xxx_0"
    }],
    "postNode": [{
        "node": "xxx_12"
    }]
},
{
    "node": "xxx_5",
    "index": "index_4",
    "status": "表达式4",
    "preNode": [{
        "node": "xxx_3"
    },
    {
        "node": "xxx_2"
    },
    {
        "node": "xxx_14"
    }],
    "postNode": [{
        "node": "xxx_6"
    }]
},
{
    "node": "xxx_6",
    "index": "index_5",
    "status": "表达式6",
    "preNode": [{
        "node": "xxx_5"
    }],
    "postNode": [{
        "node": "xxx_7"
    }]
},
{
    "node": "xxx_7",
    "index": "index_6",
    "status": "表达式7",
    "preNode": [{
        "node": "xxx_6"
    }],
    "postNode": [{
        "node": "xxx_8"
    }]
},
{
    "node": "xxx_8",
    "index": "index_4",
    "status": "表达式8",
    "preNode": [{
        "node": "xxx_7"
    }],
    "postNode": [{
        "node": "xxx_9"
    },
    {
        "node": "xxx_10"
    }]
},
{
    "node": "xxx_9",
    "index": "index_5",
    "status": "表达式5",
    "preNode": [{
        "node": "xxx_8"
    }],
    "postNode": [{
        "node": "xxx_11"
    }]
},
{
    "node": "xxx_10",
    "index": "index_7",
    "status": "表达式6",
    "preNode": [{
        "node": "xxx_8"
    }],
    "postNode": [{
        "node": "xxx_11"
    }]
},
{
    "node": "xxx_11",
    "index": "index_8",
    "status": "表达式7",
    "preNode": [{
        "node": "xxx_9"
    },
    {
        "node": "xxx_10"
    }],
    "postNode": [{
        "node": "xxx_12"
    }]
},
{
    "node": "xxx_12",
    "index": "index_8",
    "status": "表达式7",
    "preNode": [{
        "node": "xxx_11"
    },
    {
        "node": "xxx_4"
    }],
    "postNode": [{
        "node": "xxx_13"
    }]
},
{
    "node": "xxx_13",
    "index": "",
    "status": "",
    "preNode": [{
        "node": "xxx_14"
    },
    {
        "node": "xxx_12"
    }],
    "postNode": []
},
{
    "node": "9999",
    "index": null,
    "status": null,
    "preNode": [{
        "node": "xxx_14"
    },
    {
        "node": "xxx_12"
    }],
    "postNode": null
}]

项目中list对象内容

 1 JsonModel{node=‘xxx_2‘, preNode=‘‘, index=‘index_1‘, status=‘表达式1‘}
 2 JsonModel{node=‘xxx_14‘, preNode=‘‘, index=‘index_4‘, status=‘表达式5‘}
 3 JsonModel{node=‘xxx_3‘, preNode=‘‘, index=‘index_2‘, status=‘表达式2‘}
 4 JsonModel{node=‘xxx_4‘, preNode=‘‘, index=‘index_3‘, status=‘表达式3‘}
 5 JsonModel{node=‘xxx_5‘, preNode=‘xxx_2‘, index=‘index_4‘, status=‘表达式4‘}
 6 JsonModel{node=‘xxx_5‘, preNode=‘xxx_3‘, index=‘index_4‘, status=‘表达式5‘}
 7 JsonModel{node=‘xxx_5‘, preNode=‘xxx_14‘, index=‘index_4‘, status=‘表达式5‘}
 8 JsonModel{node=‘xxx_6‘, preNode=‘xxx_5‘, index=‘index_5‘, status=‘表达式6‘}
 9 JsonModel{node=‘xxx_7‘, preNode=‘xxx_6‘, index=‘index_6‘, status=‘表达式7‘}
10 JsonModel{node=‘xxx_8‘, preNode=‘xxx_7‘, index=‘index_4‘, status=‘表达式8‘}
11 JsonModel{node=‘xxx_9‘, preNode=‘xxx_8‘, index=‘index_5‘, status=‘表达式5‘}
12 JsonModel{node=‘xxx_10‘, preNode=‘xxx_8‘, index=‘index_7‘, status=‘表达式6‘}
13 JsonModel{node=‘xxx_11‘, preNode=‘xxx_10‘, index=‘index_8‘, status=‘表达式7‘}
14 JsonModel{node=‘xxx_11‘, preNode=‘xxx_9‘, index=‘index_8‘, status=‘表达式8‘}
15 JsonModel{node=‘xxx_12‘, preNode=‘xxx_11‘, index=‘index_8‘, status=‘表达式7‘}
16 JsonModel{node=‘xxx_12‘, preNode=‘xxx_4‘, index=‘index_8‘, status=‘表达式8‘}
17 JsonModel{node=‘xxx_13‘, preNode=‘xxx_14‘, index=‘‘, status=‘表达式13‘}
18 JsonModel{node=‘xxx_13‘, preNode=‘xxx_12‘, index=‘‘, status=‘表达式14‘}
public void testJson() throws Exception{
        List<JsonModel> list=new ArrayList<>();
        ObjectMapper objectMapper=new ObjectMapper();

        JsonModel jsonModel=new JsonModel("xxx_2","","index_1","表达式1");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_14","","index_4","表达式5");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_3","","index_2","表达式2");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_4","","index_3","表达式3");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_5","xxx_2","index_4","表达式4");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_5","xxx_3","index_4","表达式5");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_5","xxx_14","index_4","表达式5");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_6","xxx_5","index_5","表达式6");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_7","xxx_6","index_6","表达式7");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_8","xxx_7","index_4","表达式8");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_9","xxx_8","index_5","表达式5");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_10","xxx_8","index_7","表达式6");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_11","xxx_10","index_8","表达式7");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_11","xxx_9","index_8","表达式8");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_12","xxx_11","index_8","表达式7");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_12","xxx_4","index_8","表达式8");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_13","xxx_14","","表达式13");
        list.add(jsonModel);

        jsonModel=new JsonModel("xxx_13","xxx_12","","表达式14");
        list.add(jsonModel);

        list.forEach(var->
                System.out.println(var.toString())
        );
        System.out.println();

        //将list转成String
        String str=objectMapper.writeValueAsString(list);

        //将字符串转成JsonNode
        JsonNode rootNode = objectMapper.readTree(str);

        Set<ChildNode> preNode_set=null;
        Set<ChildNode> postNode_set=null;

        List<Node> nodeList=new ArrayList<>();

        //寻找第一个indxe 创建一个start节点
        Node node=new Node();
        node.setNode("0");
        Set<ChildNode> childNodeList=new HashSet<>();
        for(int i=0;i<rootNode.size();i++){

            if("".equals(rootNode.get(i).get("preNode").asText())){
               childNodeList.add(new ChildNode(rootNode.get(i).get("node").asText()));
            }
        }
        node.setPostNode(childNodeList);
        nodeList.add(node);

        //这种方式在如果我们只需要一个长json串中某个字段值时非常方便
        for (int i=0;i<rootNode.size();){

            preNode_set=new HashSet<>();
            postNode_set=new HashSet<>();

            //直接从rootNode中获取某个键的值,
            JsonNode nameNode = (rootNode.get(i)).get("node");
            String name = nameNode.asText();

            String index=rootNode.get(i).get("index").asText();
            String status=rootNode.get(i).get("status").asText();

            //找出后置节点  post_node
            for(int j=i+1;j<rootNode.size();j++){
                String names = (rootNode.get(j)).get("preNode").asText();

                if(name.equals(names)){

                    //  if(!"".equals(rootNode.get(j).get("postNode").asText())) {
                    postNode_set.add(new ChildNode((rootNode.get(j)).get("node").asText()));
                    //}
                }
            }

            //找前置节点
            for(int j=0;j<list.size();j++){
                String names = (rootNode.get(j)).get("node").asText();

                //对于后一个的index相同时  需要跳过
                    if(name.equals(names)){

                        if(!"".equals(rootNode.get(j).get("preNode").asText())){
                            preNode_set.add(new ChildNode((rootNode.get(j)).get("preNode").asText()));
                            if(j>i){
                                ++i;
                            }else{
                                i++;
                            }
                        }else{
                            preNode_set.add(new ChildNode("0"));
                            i++;
                        }
                    }
            }

            Node nodes=new Node();

            nodes.setIndex(index);
            nodes.setNode(name);
            nodes.setStatus(status);
            nodes.setPostNode(postNode_set);
            nodes.setPreNode(preNode_set);

            nodeList.add(nodes);

        }

        //后置节点
        Node pre_node=new Node();
        pre_node.setNode("9999");
        Set<ChildNode> childNodes=new HashSet<>();
        for(int i=0;i<rootNode.size();i++){

            //最后一个end 节点的pre_node
            if("".equals(rootNode.get(i).get("index").asText())){

                childNodes.add(new ChildNode(rootNode.get(i).get("preNode").asText()));
            }
        }
        pre_node.setPreNode(childNodes);
        nodeList.add(pre_node);

        String s = objectMapper.writeValueAsString(nodeList);
        System.out.println(s);

        System.out.println();
        jsonTest(s);

    }

    /**
     * <p>json --> 对象</p>
     * @param s
     * @throws Exception
     */
    public void jsonTest(String s) throws Exception{
        List<Node> nodeList=new ArrayList<>();
        ObjectMapper objectMapper=new ObjectMapper();
             //将字符串用objectMapper转换成jsonNode
        JsonNode jsonNode=objectMapper.readTree(s);

        List<JsonModel> jsonModels=new ArrayList<>();

        for(int i=1;i<jsonNode.size()-1;i++){
            String index=jsonNode.get(i).get("index").asText();
            String status=jsonNode.get(i).get("status").asText();
            String node=jsonNode.get(i).get("node").asText();

            for(int j=0;j<jsonNode.get(i).get("preNode").size();j++){
                String childNode= jsonNode.get(i).get("preNode").get(j).get("node").asText();
                JsonModel jsonModel=new JsonModel(node,childNode,index,status);
                jsonModels.add(jsonModel);
            }
        }
        jsonModels.forEach(val->
                System.out.println(val.toString())
        );
    }

以下是所用到的对象实体类

 1 package com.yf.af.biz.test;
 2
 3 /**
 4  * Created by chen on 2017/7/14.
 5  */
 6 public class JsonModel {
 7     private String node;
 8     private String preNode;
 9     private String index;
10     private String status;
11
12     public String getNode() {
13         return node;
14     }
15
16     public void setNode(String node) {
17         this.node = node;
18     }
19
20     public String getPreNode() {
21         return preNode;
22     }
23
24     public void setPreNode(String preNode) {
25         this.preNode = preNode;
26     }
27
28     public String getIndex() {
29         return index;
30     }
31
32     public void setIndex(String index) {
33         this.index = index;
34     }
35
36     public String getStatus() {
37         return status;
38     }
39
40     public void setStatus(String status) {
41         this.status = status;
42     }
43
44     public JsonModel(String node, String preNode, String index, String status) {
45         this.node = node;
46         this.preNode = preNode;
47         this.index = index;
48         this.status = status;
49     }
50
51     public JsonModel() {
52     }
53
54     @Override
55     public String toString() {
56         return "JsonModel{" +
57                 "node=‘" + node + ‘\‘‘ +
58                 ", preNode=‘" + preNode + ‘\‘‘ +
59                 ", index=‘" + index + ‘\‘‘ +
60                 ", status=‘" + status + ‘\‘‘ +
61                 ‘}‘;
62     }
63 }

 1 package com.yf.af.biz.test;
 2
 3 import java.util.List;
 4 import java.util.Set;
 5
 6 /**
 7  * Created by chen on 2017/7/15.
 8  */
 9 public class Node {
10     private String node;
11     private String index;
12     private String status;
13
14     private Set<ChildNode> preNode;
15
16     private Set<ChildNode> postNode;
17
18     public String getNode() {
19         return node;
20     }
21
22     public void setNode(String node) {
23         this.node = node;
24     }
25
26     public String getIndex() {
27         return index;
28     }
29
30     public void setIndex(String index) {
31         this.index = index;
32     }
33
34     public String getStatus() {
35         return status;
36     }
37
38     public void setStatus(String status) {
39         this.status = status;
40     }
41
42     public Set<ChildNode> getPreNode() {
43         return preNode;
44     }
45
46     public void setPreNode(Set<ChildNode> preNode) {
47         this.preNode = preNode;
48     }
49
50     public Set<ChildNode> getPostNode() {
51         return postNode;
52     }
53
54     public void setPostNode(Set<ChildNode> postNode) {
55         this.postNode = postNode;
56     }
57
58     @Override
59     public String toString() {
60         return "Node{" +
61                 "node=‘" + node + ‘\‘‘ +
62                 ", index=‘" + index + ‘\‘‘ +
63                 ", status=‘" + status + ‘\‘‘ +
64                 ", preNode=" + preNode +
65                 ", postNode=" + postNode +
66                 ‘}‘;
67     }
68
69
70     public Node() {
71     }
72 }

 1 package com.yf.af.biz.test;
 2
 3 /**
 4  * Created by chen on 2017/7/15.
 5  */
 6 public class ChildNode {
 7     private String node;
 8
 9     public String getNode() {
10         return node;
11     }
12
13     public void setNode(String node) {
14         this.node = node;
15     }
16
17     public ChildNode(String node) {
18         this.node = node;
19     }
20
21     public ChildNode() {
22     }
23 }

时间: 2024-07-29 12:32:00

java 对象与json互转的相关文章

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

java对象和json对象之间互相转换

一个很好的关于java对象和json对象互转的例子: 1 package com.kenneth.test; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 import java.util.Iterator; 6 import java.util.List; 7 8 import net.sf.json.JSONArray; 9 import net.sf.json.JSONObject; 10 11 /** 1

JAVA对象转化JSON出现死循环问题

主要是解决JSON因Hibernate映射生成的集合的转化出现的死循环问题. 这个方法很重要 1 public String ajaxJsonByObjectDirecdt(Object obj, String[] filterNames){ 2 JsonConfig jsonConfig = new JsonConfig(); 3 jsonConfig.setIgnoreDefaultExcludes(false); 4 jsonConfig.setCycleDetectionStrategy

FastJson、Jackson、Gson进行Java对象转换Json的细节处理

前言 Java对象在转json的时候,如果对象里面有属性值为null的话,那么在json序列化的时候要不要序列出来呢?对比以下json转换方式 一.fastJson 1.fastJson在转换java对象为json的时候,默认是不序列化null值对应的key的 也就是说当对象里面的属性为空的时候,在转换成json时,不序列化那些为null值的属性 具体案例如下: AutoPartsSearchRequest 有以下属性: public static void main(String[] args

java对象转JSON JS取JSON数据

JsonConfig config = new JsonConfig(); config.setJsonPropertyFilter(new PropertyFilter() { @Override public boolean apply(Object arg0, String arg1, Object arg2) { // 过滤掉对象里的包含自己的属性(自己关联自己) if (arg1.equals("wareTypes") || arg1.equals("skillS&

java对象与json对象间的相互转换

1.解析json字符串 将json字符串转换为json对象,然后再解析json对象:. JSONObjectjsonObject = JSONObject.fromObject(jsonStr); 根据json中的键得到它的值 Stringname = jsonObject.getString("name"); int age = jsonObject.getInt("age"); 2.将json字符串转换为java对象 同样先将json字符串转换为json对象,再

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

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

格式化java对象为json

在做java开发的时候,经常要格式化java对象,闲来无事就写了一个, 如果传递的是单个对象生成数据格式  {"id":"1","name":"名字"} 传递的是list对象生成数据格式  [{"id":"1","name":"名字"},{"id":"2","name":"名字2

java对象和json数据转换实现方式1-使用json-lib实现

测试代码: package com.yanek.util.json; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JSONLibUtil { /** * @param args */ public static void main(String[] args) { Hotel h1=new H