Hatena::ブログ(Diary)

Dieu merci


2018-04-01 json

jsonb(postgres) -> xxx.json ->java


1)postgresql 

create table:

prototype-# \d foo
 id           | integer |
 memo    | jsonb   |

insert data:

prototype=# insert into foo(id,memo) values(3,'{"name":"russia","currency":"RUB","population":"12000"}');

date are:

prototype=# select * from foo;
  3 | {"name": "russia", "currency": "RUB", "population": "12000"}
  2 | {"name": "france", "currency": "EUR", "population": "8000"}
  1 | {"name": "japan", "currency": "JPY", "population": "10000"}

2)save jsonb data in xxxx.json

prototype=#       
copy (select memo from foo where id = 1) to '/Users/tk/test.json';
COPY 1

3)read jsonb object in java class

package homeWork;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.io.FileUtils;

public class jsonSample001 {
	public static void main(String[] args) throws JsonProcessingException, IOException {
		
		
		String jsonString = FileUtils.readFileToString(new File("/Users/tk/test_foo.json"), "UTF-8");
		
		Map<String, String> jsonMap2 = JsonConverter.toObject(jsonString,
	            new TypeReference<Map<String, String>>() {
	            });
		jsonMap2.forEach ( ( key,val ) -> System.out.println( key +":" +val ) );
		
	}
}

:result

name:japan
currency:JPY
population:10000

トラックバック - http://d.hatena.ne.jp/annazola/20180401/p1