créer une hashmap à partir d'une chaîne json en java?
J'ai une chaîne json comme {"phonetype":"N95","cat":"WP"}
et je veux convertir un Hashmap standard.
Comment puis-je le faire?
Analyser le JSONObject et créer 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);
}
Sortie testée:
json : {"phonetype":"N95","cat":"WP"}
map : {cat=WP, phonetype=N95}
Vous pouvez utiliser la bibliothèque Gson de Google pour convertir json en Hashmap. Essayez ci-dessous le code
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();
}
}
}
Sortie:
{phonetype=N95, cat=WP}
Vous pouvez voir ce lien, il est utile http://www.mkyong.com/Java/how-to-convert-Java-map-to-from-json-jackson/
Vous pouvez utiliser Gson library
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
new Gson().fromJson(jsonString, type);
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;
}
Ceci est une opération simple, pas besoin d'utiliser une bibliothèque externe.
Vous pouvez utiliser cette classe à la place :) (gère même les listes, les listes imbriquées et 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;
}
}
Pour convertir votre chaîne JSON en hashmap utilisez ceci:
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Ne faites pas cela vous-même, je suggère.
Utilisez une bibliothèque, par exemple la bibliothèque Gson de Google.
Pas de bibliothèques JSON, juste String et HashMap.
Reste simple!
J'espère que cela conviendra à tous .
// Exemple de transformation JSON en HashMap basé sur String
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]);
}
Meilleure façon d'analyser Json dans 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;
}
considérez cette chaîne 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
}
]
}
en utilisant un analyseur syntaxique jackson
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;
}
utiliser le code suivant pour analyser
HashMap<String, ArrayList<Video>> integerArrayListHashMap =
JsonHandler.parseUnderScoredResponse(test, MyHashMap.class);
où se trouve MyHashMap
private static class MyHashMap extends HashMap<String,ArrayList<Video>>{
}