将点分隔的字符串转换为JSON对象

时间:2016-06-24 19:22:58

标签: java json

所以我有一个点分隔的字符串,我试图在JAVA中转换为JSON对象。结构如下。

Person.City.FirstNm.LastNm=xyz, Person.City.Address=abc. Person.City.firstNm.Salary=1000.24, Person.State.FirstNm.LastNm=xyz

等等。生成的JSON应该是这样的。请注意,值中可以有小数点。

{
    Person:
    {
        City:
        {
            firstNm:
            {
                LastNm:xyz,
                        Salary:1000.24
            },
            Address: abc
        },
        State:
        {
            FirstNm:
            {
                LastNm:xyz
            }
        }
    }
}

我曾尝试从字符串中创建一个Map,然后使用它来创建一个JSON字符串,我可以将其用作对象但没有运气。任何帮助,将不胜感激。感谢

1 个答案:

答案 0 :(得分:4)

您需要构建树状结构来存储对象。只是toString()它。以下是我看到你可以做到的事情:

public class TestJson {
    static abstract class Node {
    }

    static class IntermediateNode extends Node {
        public Map<String, Node> keyValueMap = new LinkedHashMap<>();

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            sb.append(keyValueMap.entrySet().stream().map(entry -> entry.getKey() + " : " + entry.getValue())
                       .collect(Collectors.joining(", ")));

            sb.append("}");
            return sb.toString();
        }
    }


    static class LeafNode extends Node {
        public String value;

        @Override
        public String toString() {
            return value;
        }
    }


    public static void main(String[] args) {
        String testString =
                "Person.City.FirstNm.LastNm=xyz, Person.City.Address=abc, Person.City.FirstNm.Salary=1000.24, Person"
                + ".State.FirstNm.LastNm=xyz";

        IntermediateNode root = new IntermediateNode();
        for (String param : testString.replaceAll(" ", "").split(",")) {
            String[] def = param.split("=");

            String[] result = def[0].split("\\.");
            IntermediateNode currentNode = root;
            for (int i = 0; i < result.length - 1; i++) {
                Node node = currentNode.keyValueMap.get(result[i]);
                if (node == null) {
                    IntermediateNode child = new IntermediateNode();
                    currentNode.keyValueMap.put(result[i].trim(), child);
                    currentNode = child;
                } else {
                    currentNode = (IntermediateNode) node;
                }
            }
            LeafNode leaf = new LeafNode();
            leaf.value = def[1];
            currentNode.keyValueMap.put(result[result.length - 1], leaf);
        }

        System.out.println(root);
    }
}