I have few cases where I want to convert a snake_case JSON to nested JSON eg
{
"snake_case": {
"test": "value"
}
}
to
{
"snake": {
"case": {
"test": "value"
}
}
}
Is there any way to do this in java other then manually parsing the strings with _
or there any libraries are there in java?
Consider your JSON data as String:
String strjson="{snake_case: {test: value}}";
then
JSONObject jj=new JSONObject(strjson);
JSONObject jfinal=new JSONObject();
Iterator<String> itr=jj.keys();
while(itr.hasNext())
{
String key=itr.next();
if(key.contains("-"))
{
JSONObject jkey=jj.getJSONObject(key);
JSONObject jnew=new JSONObject();
jnew.put(key.split("-")[1],jkey);
jfinal.put(key.split("-")[0],jnew);
}
}
you can get the output in jfinal.
You could BSON to achieve this. Here is the code you would use.
//import java.util.ArrayList;
//import org.bson.Document;
//Declare three json object
Document root= new Document();
Document rootSnake = new Document();
Document rootSnakeCase = new Document();
//Add value to the most nested object
rootSnakeCase.append("test","value");
//combine the objects together
if (!rootSnakeCase.isEmpty()){
rootSnake.append("case",rootSnakeCase);
}
if (!rootSnake.isEmpty()){
root.append("snake",rootSnake);
}
//output code
System.out.println(root.toJson());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.