erstellen einer Hashmap aus einem Json-String in Java?
Ich habe einen json-String wie {"phonetype":"N95","cat":"WP"}
und möchte in eine Standard-Hashmap konvertieren.
Wie kann ich es tun?
Analysieren Sie das JSONObject und erstellen Sie 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);
}
Getestete Ausgabe:
json : {"phonetype":"N95","cat":"WP"}
map : {cat=WP, phonetype=N95}
Sie können die Gson-Bibliothek von Google verwenden, um Json in Hashmap zu konvertieren. Versuchen Sie es mit dem folgenden 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();
}
}
}
Ausgabe:
{phonetype=N95, cat=WP}
Sie können diesen Link sehen, es ist hilfreich http://www.mkyong.com/Java/how-to-convert-Java-map-to-von-json-jackson/
Sie könnten Gson library verwenden
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;
}
Dies ist eine einfache Operation, ohne dass eine externe Bibliothek verwendet werden muss.
Sie können diese Klasse stattdessen verwenden :) (behandelt auch Listen, verschachtelte Listen und 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;
}
}
Um Ihre JSON-Zeichenfolge in Hashmap umzuwandeln, verwenden Sie Folgendes:
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
In Java können wir dies mit der folgenden Anweisung tun. Wir müssen dafür Jackson ObjectMapper verwenden und die HashMap.class als Mapping-Klasse bereitstellen. Speichern Sie das Ergebnis schließlich als HashMap-Objekt.
HashMap<String,String> hashMap = new ObjectMapper().readValue(jsonString, HashMap.class);
Tun Sie das nicht selbst, schlage ich vor.
Verwenden Sie eine Bibliothek, z. die Gson-Bibliothek von Google.
Keine JSON-Bibliotheken, nur String und HashMap.
Hält es einfach!
Ich hoffe es passt zu allen .
// JSON-Transformation in HashMap-Beispiel basierend auf 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]);
}
Der beste Weg, um Json zu HashMap zu parsen
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;
}
betrachten Sie diese Json-Zeichenfolge
{
"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
}
]
}
mit Jackson Parser
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;
}
verwenden Sie den folgenden Code zum Analysieren
HashMap<String, ArrayList<Video>> integerArrayListHashMap =
JsonHandler.parseUnderScoredResponse(test, MyHashMap.class);
wo MyHashMap ist
private static class MyHashMap extends HashMap<String,ArrayList<Video>>{
}