简体   繁体   English

如何在Java中预处理Json字符串::将大写的字段名称转换为小写的驼峰式名称

[英]How to Pre Process Json String in Java :: Convert Capitalised Field names to lowerCase Camel case names

My current Android project consumes many Json web services. 我当前的Android项目使用了许多Json Web服务。

I have no control over the Json content. 我无法控制Json内容。

I wish to persist this Json directly into my applications local Realm database. 我希望将此Json直接保留到我的应用程序本地Realm数据库中。

The issue is the Json Field Names Are All Capitalised. 问题是“ Json字段名称全部大写”。

I do not wish my Realm DTO objects to have capitalised field names as thats just WRONG. 我不希望我的Realm DTO对象具有大写的字段名,这就是错误的。

How can I transform the Capitalised field names to acceptable Java field name format? 如何将大写的字段名称转换为可接受的Java字段名称格式?

Is there any Json pre processing libraries that will perform the required transformation of Capitalised field names? 是否有任何Json预处理库将执行所需的大写字段名称转换?

I realise I can use Jackson/GSON type libraries to solve this issue, however that means transforming Json to Java Pojo before I can persist the data. 我意识到我可以使用Jackson / GSON类型库来解决此问题,但是这意味着在我可以持久存储数据之前将Json转换为Java Pojo。

The json Field names are "ThisIsAFieldName". json字段名称为“ ThisIsAFieldName”。

What I want is to transform them to "thisIsAFieldName". 我想要的是将它们转换为“ thisIsAFieldName”。

I think you should really consider letting your JSON deserializer handle this, but if this really isn't a possibility you can always use good old string manipulation : 我认为您应该真正考虑让JSON解串器处理此问题,但是,如果确实没有这种可能性,则可以始终使用良好的旧字符串操作:

String input; // your JSON input
Pattern p = Pattern.compile("\"([A-Z])([^\"]*\"\\s*:)"); // matches '"Xxxx" :'
Matcher m = p.matcher(input);
StringBuffer output = new StringBuffer();
while (m.find()) {
   m.appendReplacement(output, String.format("\"%s$2", m.group(1).toLowerCase());
}
m.appendTail(output);

Ideone test . ideone测试

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM