Hector
Hector

Reputation: 5418

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.

I have no control over the Json content.

I wish to persist this Json directly into my applications local Realm database.

The issue is the Json Field Names Are All Capitalised.

I do not wish my Realm DTO objects to have capitalised field names as thats just WRONG.

How can I transform the Capitalised field names to acceptable Java field name format?

Is there any Json pre processing libraries that will perform the required transformation of Capitalised field names?

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.

The json Field names are "ThisIsAFieldName".

What I want is to transform them to "thisIsAFieldName".

Upvotes: 0

Views: 291

Answers (1)

Aaron
Aaron

Reputation: 24812

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 :

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.

Upvotes: 1

Related Questions