通过拆分字符串创建JSON?

时间:2018-08-03 16:34:35

标签: java json spring-rest jsonparser

因此,我遇到了无法从数据库中获取某些无法更改/更新的数据的情况。所以我从2列中获得的数据是这样的:

例如

        Column1             Column2
Row 1: hello.how.are.you    Gracie
Row 2: hello.how.is.she     John
Row 3: hello.how.is.he      Gurinder   
Row 4: hello.from.me        Singh

所以我需要创建一个如下所示的JSON:

{  
   "hello":{  
      "how":{  
         "are":{  
            "you":"Gracie"
         },
         "is":{  
            "he":"Gurinder",
            "she":"John"
         }
      },
      "from":{  
         "me":"Singh"
      }
   }
}

我想要一些优化的方法来创建我的JSON。谢谢!

public static void main(String[] args) {

    List<String > stringList = new ArrayList();
    stringList.add("hello.how.are.you");
    stringList.add("hello.how.is.she");
    stringList.add("hello.how.is.he");
    stringList.add("hello.from.me");

    JSONObject response = new JSONObject();

    for (String str : stringList) {

            String[] keys = str.split("\\.");

            for (int i = 0; i < keys.length; i++) {

                if (response.has(keys[i])) {

                } else {
                    JSONObject jsonObject2 = new JSONObject()
                    response.append(keys[i], jsonObject2);

                }
            }
        }
    }

我正在做类似的事情,并试图解决。

2 个答案:

答案 0 :(得分:0)

用于输入的内容需要保存所有数据(包括第2列)。假设input变量是等于{p>的HashMap<String, String>

{
    "hello.how.are.you" : "Gracie",
    ...
}

目前,您的代码看起来像是正确的。问题是,当您想附加到JSON树深处的某个值时,您将附加到response

JSONObject parent = response;
for(...) {
    // If there's no JSON there, just make it
    if( !parent.has(keys[i]) ) {
        // It's not already in there, so let's make it
        parent.put(keys[i], new JSONObject()); // response["hello"] = {}
    }
    // Now, look at how this works. If keys = ["hello", "how", "are", "you"],
    // Then when i == 0, parent <= response["hello"]
    // That way you do response["hello"].append("how", {}) on the next iteration
    parent = (JSONObject)parent.get(keys[i]);
}

您还需要处理尾箱,您可以使用类似的方法

if( i == keys.length - 1 ) {
    parent.put(keys[i], input.get(str)); // str = "hello.how.are.you"
    // input.get("hello.how.are.you") == "Gracie"
} else ...

答案 1 :(得分:0)

所以我通过使用这种方法解决了这个问题:

    public static void main(String... r) {

    String[] keys = myString.split("//.");

    JSONObject target = new JSONObject();

    int lastValueIndex = keys.length - 1;

    for (int i = 0; i < keys.length; i++) {

        String key = keys[i];

        if (!target.has(key) && (lastValueIndex == i)) {

            target.put(key, myValue);

            break;

        } else if (!target.has(key)) {
            target.put(key, new JSONObject());
        }

        target = target.getJSONObject(key);

    }

}

在使用我的代码之前尝试一下自己的方式,谢谢!