简体   繁体   English

我应该如何将 JSON 有效载荷的大小写转换为小驼峰大小写?

[英]How should I convert the case of a JSON payload to lower camel case?

I'm dealing with JSON whose property names are snake-cased, but, I need these transformed into a lower camel case.我正在处理 JSON 的属性名称是蛇形的,但是,我需要将它们转换成一个小驼峰式。

I don't have beans for all the corresponding objects so the usual ser-de tricks of Jackson don't apply (I think).我没有所有相应对象的 bean,因此 Jackson 的常用 ser-de 技巧不适用(我认为)。

I tried reading it into a Map and setting a global property naming strategy but that didn't work.我尝试将其读入Map并设置全局属性命名策略,但这不起作用。

    String json = "{\"first_name\": \"John\", \"last_name\": \"Doe\" }";

    Map<?, ?> myMap = new ObjectMapper().readValue(json, Map.class);
    System.out.println(new ObjectMapper()
            .setPropertyNamingStrategy(new UpperCamelCaseStrategy())
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(myMap));

I don't need this to be necessarily accomplished in Jackson.我不需要这必须在 Jackson 中完成。 While a simple problem, it did leave me quite lost as to what a sane way of accomplishing this might be.虽然是一个简单的问题,但它确实让我非常迷茫,不知道实现这一点的明智方法可能是什么。

I found this solution, which is a bit hard-coded, using regex.我使用正则表达式找到了这个有点硬编码的解决方案。 In this way, however, you do not need to use any JsonObject library.但是,通过这种方式,您不需要使用任何JsonObject库。

I wrote three methods:我写了三个方法:

  1. one to convert a string from snake_case to pascalCase一个将字符串从 snake_case 转换为 pascalCase

     private static String convertToPascalCase(String str){ while(str.contains("_")) { str = str.replaceFirst("_[az]", String.valueOf(Character.toUpperCase(str.charAt(str.indexOf("_") + 1)))); } return str; }
  2. Another which handles the replacing of the regex matches另一个处理正则表达式匹配的替换

    private static String replaceMatches(Matcher m, Function<MatchResult, String> mapping) { StringBuffer sb = new StringBuffer(); while (m.find()) { MatchResult matchResult = m.toMatchResult(); m.appendReplacement(sb, mapping.apply(matchResult)); } m.appendTail(sb); return sb.toString(); }
  3. the last one which defines the appropriate regex and then calls replaceMatches最后一个定义适当的正则表达式,然后调用replaceMatches

     public static String convertToPascalCaseAllJsonKeys(String jsonString) { Pattern p = Pattern.compile("\"(\\w+)\":"); Matcher m = p.matcher(jsonString); return replaceMatches(m, mr -> "\"" + convertToPascalCase(mr.group(1)) + "\":"); }

The usage is the following:用法如下:

String json = "{\"first_name\": \"John\", \"last_name\": \"Doe\", \"children\": [\"Jane\", \"Mary\", \"Harry\"]}";
String jsonWithPascalKey = convertToPascalCaseAllJsonKeys(json);

System.out.println(jsonWithPascalKey );
// result: {"firstName": "John", "lastName": "Doe", "children": ["Jane", "Mary", "Harry"]}

Then, you can easily convert the string to a JsonObject.然后,您可以轻松地将字符串转换为 JsonObject。

https://github.com/octomix/josson https://github.com/octomix/josson

If the JSON has one level.如果 JSON 有一级。

Josson josson = Josson.fromJsonString("{\"first_name\": \"John\", \"last_name\": \"Doe\"}");
JsonNode node = josson.getNode("entries().map(key.camelCase()::value).mergeObjects()");
System.out.println(node.toPrettyString());

Output Output

{
  "firstName" : "John",
  "lastName" : "Doe"
}

Nest the transformation query one more time for each additional level.对于每个附加级别,再嵌套一次转换查询。

Josson josson = Josson.fromJsonString("{\"sales_person\":{\"first_name\": \"John\", \"last_name\": \"Doe\"}}");
JsonNode node = josson.getNode(
    "entries()" +
    ".map(key.camelCase()" +
    "     ::value.entries()" +
    "       .map(key.camelCase()" +
    "            ::value)" +
    "       .mergeObjects())" +
    ".mergeObjects()");
System.out.println(node.toPrettyString());

Output Output

{
  "salesPerson" : {
    "firstName" : "John",
    "lastName" : "Doe"
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 REST API 中将骆驼大小写转换为带下划线的小写字母? - How to convert camel case to lower case with underscores in a REST API? "当有连续的​​大写字母时,如何在Java中将骆驼大小写转换为低连字符" - How to convert Camel Case to Lower Hyphen in Java when there are contiguous capitals 在swagger.json中没有反映CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES - CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES not reflected in swagger.json 在jhipster项目中将实体属性驼峰案例转换为json中的蛇案例 - Convert entity property camel case to snake case in json in jhipster project 如何将小写字母转换为大写字母 &amp; 以及将大写字母转换为小写字母 - how to convert Lower case letters to upper case letters & and upper case letters to lower case letters 如何将文本文件转换为小写并找到字母的频率? - How do i convert a textfile to lower case and find the frequencies of the letters? 将hashmap转换为小写 - convert hashmap to lower case 我正在尝试将字符串从小写转换为大写,将大写转换为小写 - I am trying to convert a string from lower case to upper case and upper case to lower casee 如何将大写字符串转换为Camel Case并保持首字母缩略词不变? - How to Convert Upper case string to Camel Case and keeping the Acronyms as it is? 无法使用 Jackson 将下划线大小写转换为驼色大小写 - Not able to convert underscore case to camel case with Jackson
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM