0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSON-java(org.json)で項目値のnullを空文字して、空要素を<タグ />から<タグ></タグ>に加工する方法

Last updated at Posted at 2024-12-18

試したコードの一部

Java 17

// JSON文字列
String jsonString = """
{
    "b": "value_b",
    "a": "value_a",
    "c": null
}
""";

JSONObject jsonObject = new JSONObject(jsonString);

// nullを空文字に置き換え
for (String key : jsonObject.keySet()) {
    if (jsonObject.isNull(key)) {
        jsonObject.put(key, ""); // 空文字に置き換え
    }
}
 
// XMLに変換
String xml = XML.toString(jsonObject);

// 空要素形式 (<タグ/>) を置換して (<タグ></タグ>) に変更
xml = xml.replaceAll("<(\\w+)/>", "<$1></$1>");

// 結果を表示
System.out.println(xml);

結果

<a>value_a</a><b>value_b</b><c></c>

JSON を XML に変換する際に、値が null または空の場合にタグを削除

// JSON文字列
String jsonString = """
{
    "name": "John",
    "age": null,
    "address": "",
    "city": "Tokyo"
}
""";

JSONObject jsonObject = new JSONObject(jsonString);

// 値がnullまたは空のキーを削除
removeEmptyValues(jsonObject);
 
// XMLに変換
String xml = XML.toString(jsonObject);

// 結果を表示
System.out.println(xml);
private static void removeEmptyValues(JSONObject jsonObject) {
    // JSONのキーを反復処理するためのIteratorを取得
    Iterator<String> keys = jsonObject.keys();

    // Iteratorを使って安全にキーを削除
    while (keys.hasNext()) {
        String key = keys.next();
        Object value = jsonObject.get(key);

        // nullまたは空文字列の場合にキーを削除
        if (value == JSONObject.NULL || (value instanceof String && ((String) value).isEmpty())) {
            keys.remove(); // Iterator経由で削除
        }
    }
}

結果

<city>Tokyo</city><name>John</name>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?