Java查询字符串到JSON

时间:2016-01-31 05:23:22

标签: java json

给定一个包含简单类型(字符串,日期),数组和复杂对象的查询字符串,如何使用Java轻松创建JSON表示?

例如:

type=event&groups%5B%5D=a&groups%5B%5D=b&details%5Bclient_time%5D=Sat+Jan+30+2016+18%3A38%3A57+GMT-0500+(EST)

应该产生:

{ type: 'event', groups: [ 'a', 'b' ], details: { client_time: 'Sat Jan 30 2016 18:38:57 GMT-0500 (EST)' } }

这样的功能存在于Node.js Express框架中(结果很容易作为request.query提供)。

1 个答案:

答案 0 :(得分:0)

我仍然不确定(根据问题的评论)原始字符串格式正确。我认为当你用虚拟数据替换值时,一些字符会被移动。我不认为从原始字符串到序列化字符串的逻辑转换

看看这个

final String opString = "type=event&groups%5B%5D=a&groups%5B%5D=b&details%5Bclient_time%5D=Sat+Jan+30+2016+18%3A38%3A57+GMT-0500+(EST)";

System.out.println(URLDecoder.decode(opString, "UTF-8"));

输出

type=event&groups[]=a&groups[]=b&details[client_time]=Sat Jan 30 2016 18:38:57 GMT-0500 (EST)

我对你的字符串的解释

final String  myString = "type%3Devent%26groups%3D%5B%27a%27%2C%27b%27%5D%26details%5Bclient_time%5D=Sat+Jan+30+2016+18%3A38%3A57+GMT-0500+(EST)";
    System.out.println(URLDecoder.decode(myString, "UTF-8"));

输出

type=event&groups=['a','b']&details[client_time]=Sat Jan 30 2016 18:38:57 GMT-0500 (EST)

我可以在逻辑上使用它来生成你想要的字符串

    final String myStringDecoded = URLDecoder.decode(myString, "UTF-8");

    System.out.println(myStringDecoded);

    // Then we can break it down to its parts
    // The & is used to operate values
    String[] parts = myStringDecoded.split("&");


    JsonObject json = new JsonObject();

    for(String part: parts){
      String[] keyVal = part.split("="); // The equal separates key and values
        json.addProperty(keyVal[0], keyVal[1]);
    }

    System.out.println(json);

导致

{"type":"event","groups":"['a','b']","details[client_time]":"Sat Jan 30 2016 18:38:57 GMT-0500 (EST)"}

如果我的假设是正确的话,我可以改进这个答案,使其完全符合您的要求