简体   繁体   English

如何在Java中将snake_case JSON转换为嵌套JSON?

[英]How to convert a snake_case JSON to nested JSON in java?

I have few cases where I want to convert a snake_case JSON to nested JSON eg 我在少数情况下想将snake_case JSON转换为嵌套JSON,例如

{
    "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? 除了用_手动解析字符串外,是否有其他方法可以在Java中执行此操作,或者Java中是否有任何库?

Consider your JSON data as String: 将您的JSON数据视为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. 您可以在jfinal中获得输出。

You could BSON to achieve this. 您可以BSON实现这一目标。 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());

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

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