javaでjson文字列からハッシュマップを作成しますか?
{"phonetype":"N95","cat":"WP"}
のようなjson文字列があり、標準のハッシュマップに変換したい。
どうすればできますか?
JSONObjectを解析してHashMapを作成します
public static void jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
System.out.println("json : "+jObject);
System.out.println("map : "+map);
}
テスト済みの出力:
json : {"phonetype":"N95","cat":"WP"}
map : {cat=WP, phonetype=N95}
GoogleのGsonライブラリを使用して、jsonをハッシュマップに変換できます。以下のコードを試してください
String jsonString = "Your JSON string";
HashMap<String,String> map = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, String>>(){}.getType());
public class JsonMapExample {
public static void main(String[] args) {
String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Map<String, String> map = new HashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
try {
//convert JSON string to Map
map = mapper.readValue(json, new TypeReference<HashMap<String, String>>() {});
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
出力:
{phonetype=N95, cat=WP}
このリンクが役立つことを確認できます http://www.mkyong.com/Java/how-to-convert-Java-map-to-from-json-jackson/
Gson libraryを使用できます
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
new Gson().fromJson(jsonString, type);
これは、外部ライブラリを使用する必要のない単純な操作です。
代わりにこのクラスを使用できます:)(リスト、ネストされたリスト、jsonを処理します)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
JSON string to hashmapを変換するには、これを使用します:
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
HashMap<String, String> hashMap = new HashMap<String, String>();
String string = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
try {
JSONObject json = new JSONObject(string);
hashMap.put("phonetype", json.getString("phonetype"));
hashMap.put("cat", json.getString("cat"));
} catch (JSONException e) {
// TODO Handle expection!
}
public Map<String, String> parseJSON(JSONObject json, Map<String, String> dataFields) throws JSONException {
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
String val = null;
try {
JSONObject value = json.getJSONObject(key);
parseJSON(value, dataFields);
} catch (Exception e) {
if (json.isNull(key)) {
val = "";
} else {
try {
val = json.getString(key);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
if (val != null) {
dataFields.put(key, val);
}
}
return dataFields;
}
Javaでは、次のステートメントを使用して実行できます。同じためにJackson ObjectMapperを使用し、マッピングクラスとしてHashMap.classを提供する必要があります。最後に、結果をHashMapオブジェクトとして保存します。
HashMap<String,String> hashMap = new ObjectMapper().readValue(jsonString, HashMap.class);
自分でこれをしないでください。
ライブラリを使用します。 GoogleのGsonライブラリ。
JSONライブラリはなく、StringとHashMapのみ。
シンプルに保ちます!
それがすべてに適していることを願っています。
//文字列に基づくHashMapへのJSON変換の例
String tempJson = "{\"incomePhone\":\"213121122\",\"clientId\":\"1001\",\"clientAccountManager\":\"Gestor de Conta 1\",\"clientRetailBranch\":\"100\",\"phoneAccountManager\":\"7800100\"}";
System.out.println(tempJson);
String[] parts = tempJson.split(",");
HashMap<String,String> jsonHash = new HashMap<String,String>();
for(int i=0;i<parts.length;i++){
parts[i] = parts[i].replace("\"", "");
parts[i] = parts[i].replace("{", "");
parts[i] = parts[i].replace("}", "");
String[] subparts = parts[i].split(":");
jsonHash.put(subparts[0],subparts[1]);
}
JsonをHashMapに解析する最良の方法
public static HashMap<String, String> jsonToMap(JSONObject json) throws JSONException {
HashMap<String, String> map = new HashMap<>();
try {
Iterator<String> iterator = json.keys();
while (iterator.hasNext()) {
String key = iterator.next();
String value = json.getString(key);
map.put(key, value);
}
return map;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
このJSON文字列を検討してください
{
"12": [
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/12/12_960x540_200k.mp4/manifest.mpd",
"video_bitrate": "200k",
"audio_bitrate": "32k",
"video_width": 960,
"video_height": 540,
"file_size": 125465600
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/12/12_960x540_80k.mp4/manifest.mpd",
"video_bitrate": "80k",
"audio_bitrate": "32k",
"video_width": 960,
"video_height": 540,
"file_size": 50186240
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/12/12_640x360_201k.mp4/manifest.mpd",
"video_bitrate": "201k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 145934731
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/12/12_640x360_199k.mp4/manifest.mpd",
"video_bitrate": "199k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 145800030
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/12/12_640x360_79k.mp4/manifest.mpd",
"video_bitrate": "79k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 71709477
}
],
"13": [
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/13/13_960x540_200k.mp4/manifest.mpd",
"video_bitrate": "200k",
"audio_bitrate": "32k",
"video_width": 960,
"video_height": 540,
"file_size": 172902400
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/13/13_960x540_80k.mp4/manifest.mpd",
"video_bitrate": "80k",
"audio_bitrate": "32k",
"video_width": 960,
"video_height": 540,
"file_size": 69160960
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/13/13_640x360_201k.mp4/manifest.mpd",
"video_bitrate": "201k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 199932081
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/13/13_640x360_199k.mp4/manifest.mpd",
"video_bitrate": "199k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 199630781
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/13/13_640x360_79k.mp4/manifest.mpd",
"video_bitrate": "79k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 98303415
}
],
"14": [
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/14/14_960x540_200k.mp4/manifest.mpd",
"video_bitrate": "200k",
"audio_bitrate": "32k",
"video_width": 960,
"video_height": 540,
"file_size": 205747200
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/14/14_960x540_80k.mp4/manifest.mpd",
"video_bitrate": "80k",
"audio_bitrate": "32k",
"video_width": 960,
"video_height": 540,
"file_size": 82298880
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/14/14_640x360_201k.mp4/manifest.mpd",
"video_bitrate": "201k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 237769546
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/14/14_640x360_199k.mp4/manifest.mpd",
"video_bitrate": "199k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 237395552
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/14/14_640x360_79k.mp4/manifest.mpd",
"video_bitrate": "79k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 116885686
}
],
"15": [
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/15/15_960x540_200k.mp4/manifest.mpd",
"video_bitrate": "200k",
"audio_bitrate": "32k",
"video_width": 960,
"video_height": 540,
"file_size": 176128000
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/15/15_960x540_80k.mp4/manifest.mpd",
"video_bitrate": "80k",
"audio_bitrate": "32k",
"video_width": 960,
"video_height": 540,
"file_size": 70451200
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/15/15_640x360_201k.mp4/manifest.mpd",
"video_bitrate": "201k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 204263286
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/15/15_640x360_199k.mp4/manifest.mpd",
"video_bitrate": "199k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 204144447
},
{
"dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/15/15_640x360_79k.mp4/manifest.mpd",
"video_bitrate": "79k",
"audio_bitrate": "32k",
"video_width": 640,
"video_height": 360,
"file_size": 100454382
}
]
}
ジャクソンパーサーを使用して
private static ObjectMapper underScoreToCamelCaseMapper;
static {
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
underScoreToCamelCaseMapper = new ObjectMapper();
underScoreToCamelCaseMapper.setDateFormat(df);
underScoreToCamelCaseMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
underScoreToCamelCaseMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
underScoreToCamelCaseMapper.setPropertyNamingStrategy(
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
public static <T> T parseUnderScoredResponse(String json, Class<T> classOfT) {
try {
if (json == null) {
return null;
}
return underScoreToCamelCaseMapper.readValue(json, classOfT);
} catch (JsonParseException e) {
} catch (JsonMappingException e) {
} catch (IOException e) {
}
return null;
}
次のコードを使用して解析する
HashMap<String, ArrayList<Video>> integerArrayListHashMap =
JsonHandler.parseUnderScoredResponse(test, MyHashMap.class);
myHashMapは
private static class MyHashMap extends HashMap<String,ArrayList<Video>>{
}