1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javaで扱うJSONを振り返る

Posted at

#前書き
JSONを扱うにあたり知識が抜けていることに気がついた。
これだけあればjavaで最低限JSONの扱いは可能というレベルまでまとめたいと思う
(ライブラリはJSONICを利用)

#JSONの基本
JavaでJSONを扱うといったらJSONの書式で書かれたStringを扱うこと
 String→POJO
 POJO→String  など

###JSONの書式ルール(読み方)
 ①リスト構造は[ ]で囲われる
 ②POJO構造は{ }で囲われる
 ③一番親となるPOJO構造の名前を指定している部分はない
 以上3つを覚えておくとすぐ読めると思う

サンプル

 {
    "id": 1,
    "name": "shoes",
    "price": 12000,
    "shops": [
      {
         "name": "Astore",
         "location": "tokyo"
      },
      {
         "name": "Bstore",
         "location": "oosaka"
      }
    ]
 }

サンプルのPOJO

	public class Product {
		public Integer id;
		public String name;
		public Integer price;
		public List<Shop> shops;
	}

	public class Shop {
		public String name;
		public String location;
	}

##Jacksonの扱い
上記のJSONとPOJOを使った場合

###JSON→Java

		String json = "{\"id\": 1,\"name\": \"shoes\",\"price\": 12000,\"shops\": [{\"name\": \"Astore\",\"location\": \"tokyo\"},{\"name\": \"Bstore\",\"location\": \"oosaka\"}]}";
		ObjectMapper mapper = new ObjectMapper();
		Product data = mapper.readValue(json, Product.class);

リストやマップの構造で送られてきた場合

		ObjectMapper mapper = new ObjectMapper();
		List<Product> products = mapper.readValue(json, new TypeReference<List<Product>>() {});

###Java→JSON

		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(product);

###その他
・POJOは各propertyがpulicであるかGetter/Setterを持っていないとエラーになる
・JSON→Javaの変換時にPOJOが持たないpropertyがあるとエラーになる
  → POJOに「@JsonIgnoreProperties(ignoreUnknown=true)」をつけるとエラーにならない
  → 必要なデータだけを抜き出すことができる

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?