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?

(調査中)JacksonでJSON文字列を順序付きに変換 / XML文字列を順序付きに変換

Last updated at Posted at 2024-12-02

JacksonでJSON文字列を順序付きに変換

手順:

JacksonのObjectMapperを使えば、簡単にJSON文字列をLinkedHashMapとしてデシリアライズできます。

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.LinkedHashMap;

public class JacksonJsonExample {
    public static void main(String[] args) {
        // JSON文字列
        String jsonString = "{\"city\":\"New York\",\"name\":\"Alice\",\"age\":30}";

        try {
            // ObjectMapperの準備
            ObjectMapper mapper = new ObjectMapper();

            // JSON文字列をLinkedHashMapに変換
            LinkedHashMap<String, Object> map = mapper.readValue(jsonString, LinkedHashMap.class);

            // 順序が保持されていることを確認
            System.out.println(map);

            // 再度JSON文字列に戻す
            String orderedJsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
            System.out.println(orderedJsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

結果

{city=New York, name=Alice, age=30}

{
  "city" : "New York",
  "name" : "Alice",
  "age" : 30
}

JacksonでXML文字列を順序付きに変換

JacksonはXML用の拡張モジュール(jackson-dataformat-xml)を利用して、XMLをLinkedHashMapに変換できます。

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.util.LinkedHashMap;

public class JacksonXmlExample {
    public static void main(String[] args) {
        // XML文字列
        String xmlString = "<root><city>New York</city><name>Alice</name><age>30</age></root>";

        try {
            // XmlMapperの準備
            XmlMapper xmlMapper = new XmlMapper();

            // XML文字列をLinkedHashMapに変換
            LinkedHashMap<String, Object> map = xmlMapper.readValue(xmlString, LinkedHashMap.class);

            // 順序が保持されていることを確認
            System.out.println(map);

            // 再度XML文字列に戻す
            String orderedXmlString = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
            System.out.println(orderedXmlString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
{city=New York, name=Alice, age=30}

<LinkedHashMap>
  <city>New York</city>
  <name>Alice</name>
  <age>30</age>
</LinkedHashMap>
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?