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?

More than 3 years have passed since last update.

【メモ】 JSON 概要

Last updated at Posted at 2021-03-28

JSONを初めて使用したので、概要だけまとめておく。

おおむね、下記の3パターンを階層的に組み合わせていく。

オブジェクト型

json

{
	"id": "001",
	"name": "taro"
}

java

// マッピング
JsonSampleBean bean = mapper.readValue(json, JsonSampleBean.class);

// Beanの定義
package com.example.app.bean.json.request;

import lombok.Getter;
import lombok.Setter;

/**
 * JSONマッピング用のオブジェクト。
 *
 * @author start
 */
public class JsonSampleBean {

	/** ID */
	@Getter
	@Setter
	private String id;

	/** 名称 */
	@Getter
	@Setter
	private String name;

}

リスト(配列)型

json

{
	"sampleList": [
		{
			"id": "001",
			"name": "taro"
		},
		{
			"id": "002",
			"name": "jiro"
		}
	]
}

java

// マッピング
JsonSampleListBean list = mapper.readValue(listJson, JsonSampleListBean.class);

// Beanの定義
package com.example.app.bean.json.request;

import java.util.List;

import lombok.Getter;
import lombok.Setter;

/**
 * JSONマッピング用のオブジェクト。
 *
 * @author start
 */
public class JsonSampleListBean {

	/** リスト */
	@Getter
	@Setter
	private List<JsonSampleBean> sampleList;

}

リスト(配列)型_リストのみ

json

[
	{
		"id": "001",
		"name": "taro"
	},
	{
		"id": "002",
		"name": "jiro"
	}
]

java

// マッピング
List<JsonSampleBean> list = mapper.readValue(listJson, new TypeReference<List<JsonSampleBean>>(){});

// Beanの定義
// 省略

マップ型

json

{
    "sampleMap":{
    	"key1": {
    		"id": "001",
    		"name": "taro"
    	},
    	"key2": {
    		"id": "002",
    		"name": "jiro"
    	}
    }
}

java

// マッピング
JsonSampleMapBean map = mapper.readValue(mapJson, JsonSampleMapBean.class);

// Beanの定義
package com.example.app.bean.json.request;

import java.util.Map;

import lombok.Getter;
import lombok.Setter;

/**
 * JSONマッピング用のオブジェクト。
 *
 * @author start
 */
public class JsonSampleMapBean {

	/** マップ */
	@Getter
	@Setter
	private Map<String, JsonSampleBean> sampleMap;

}

マップ型_マップのみ

json

{
	"key1": {
		"id": "001",
		"name": "taro"
	},
	"key2": {
		"id": "002",
		"name": "jiro"
	}
}

java

// マッピング
Map<String, JsonSampleBean> map = mapper.readValue(mapJson, new TypeReference<LinkedHashMap<String,JsonSampleBean>>(){});

// Beanの定義
// 省略
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?