een hashmap maken van een json-tekenreeks in java?
Ik heb een json-tekenreeks zoals {"phonetype":"N95","cat":"WP"}
en wil deze converteren naar een standaard Hashmap.
Hoe kan ik dat doen?
Antwoord 1, autoriteit 100%
Ontdek het JSONObject en maak 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);
}
Geteste uitvoer:
json : {"phonetype":"N95","cat":"WP"}
map : {cat=WP, phonetype=N95}
Antwoord 2, autoriteit 69%
U kunt de Gson-bibliotheek van Google gebruiken om json naar Hashmap te converteren. Probeer onderstaande code
String jsonString = "Your JSON string";
HashMap<String,String> map = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, String>>(){}.getType());
Antwoord 3, autoriteit 26%
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();
}
}
}
Uitvoer:
{phonetype=N95, cat=WP}
Je kunt deze link zien, het is handig http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
Antwoord 4, autoriteit 9%
U kunt de Gson-bibliotheek
gebruiken
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
new Gson().fromJson(jsonString, type);
5
Doe dit niet zelf te doen, stel ik voor.
Met een bibliotheek, b.v. de Gson bibliotheek van Google.
https://code.google.com/p/google-gson/
Antwoord 6
Geen JSON-bibliotheken, alleen String en HashMap.
Houdt het simpel!
Hoop dat het bij iedereen past.
// JSON Transform to HashMap-voorbeeld op basis van 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]);
}
Antwoord 7
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;
}
Antwoord 8
Beste manier om Json te ontleden naar 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;
}
Antwoord 9
In Java kunnen we dit doen met de volgende instructie . We moeten hiervoor Jackson ObjectMapper gebruiken en de HashMap.class opgeven als de mapping-klasse. Sla ten slotte het resultaat op als een HashMap-object.
HashMap<String,String> hashMap = new ObjectMapper().readValue(jsonString, HashMap.class);
Antwoord 10
Dit werkte voor mij:
JSONObject jsonObj = new JSONObject();
jsonObj.put("phonetype","N95");
jsonObj.put("cat","WP");
jsonObj naar Hashmap als volgt met gson
HashMap<String, Object> hashmap = new Gson().fromJson(jsonObj.toString(), HashMap.class);
pakket gebruikt
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>
Antwoord 11
Hier is een voorbeeld van een gemakkelijke en eenvoudige manier om een Hashmap van een JSON-tekenreeks te maken door alleen de JSON-eenvoudige bibliotheek te gebruiken:
{“Collection”:{“Item_Type”:”Elke”,”Name”:”A”,”Item_ID”:”000014″},”Object_Name”:”Systeem”}
import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.*;
public class JSONRead {
public static void main(String[] args) throws Exception {
Object obj = new JSONParser().parse(new FileReader("D:\\other.json"));
HashMap<String,String> map =new HashMap<String,String>();
// typecasting obj to JSONObject
JSONObject jo = (JSONObject) obj;
Map Item_Id = ((Map)jo.get("Collection"));
Iterator<Map.Entry> itr1 = Item_Id.entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
String key = (String) pair.getKey();
String value = (String) pair.getValue();
System.out.println( pair.getKey() + " : " + pair.getValue());
map.put(key, value);
}
System.out.println(map)
System.out.println(map.get("Item"));
}
Antwoord 12
Je zou Jackson hiervoor kunnen gebruiken. Ik moet nog een eenvoudige Gson-oplossing vinden.
Waar data_map.json
een JSON-bronbestand (object) is
en data_list.json
is een JSON (array) bronbestand.
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Based on:
*
* http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
*/
public class JsonLoader {
private static final ObjectMapper OBJ_MAPPER;
private static final TypeReference<Map<String,Object>> OBJ_MAP;
private static final TypeReference<List<Map<String,Object>>> OBJ_LIST;
static {
OBJ_MAPPER = new ObjectMapper();
OBJ_MAP = new TypeReference<Map<String,Object>>(){};
OBJ_LIST = new TypeReference<List<Map<String,Object>>>(){};
}
public static void main(String[] args) {
try {
System.out.println(jsonToString(parseJsonString(read("data_map.json", true))));
System.out.println(jsonToString(parseJsonString(read("data_array.json", true))));
} catch (IOException e) {
e.printStackTrace();
}
}
private static final Object parseJsonString(String jsonString) {
try {
if (jsonString.startsWith("{")) {
return readJsonObject(jsonString);
} else if (jsonString.startsWith("[")) {
return readJsonArray(jsonString);
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String jsonToString(Object json) throws JsonProcessingException {
return OBJ_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(json);
}
private static final Map<String,Object> readJsonObject(String jsonObjectString) throws JsonParseException, JsonMappingException, IOException {
return OBJ_MAPPER.readValue(jsonObjectString, OBJ_MAP);
}
private static final List<Map<String,Object>> readJsonArray(String jsonArrayString) throws JsonParseException, JsonMappingException, IOException {
return OBJ_MAPPER.readValue(jsonArrayString, OBJ_LIST);
}
public static final Map<String,Object> loadJsonObject(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
return OBJ_MAPPER.readValue(load(path, isResource), OBJ_MAP);
}
public static final List<Map<String,Object>> loadJsonArray(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException {
return OBJ_MAPPER.readValue(load(path, isResource), OBJ_LIST);
}
private static final URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
if (isResource) {
return JsonLoader.class.getClassLoader().getResource(path);
}
return new URL("file:/" + path);
}
protected static File load(String path, boolean isResource) throws MalformedURLException {
return load(pathToUrl(path, isResource));
}
protected static File load(URL url) {
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
return new File(url.getPath());
}
}
public static String read(String path, boolean isResource) throws IOException {
return read(path, "UTF-8", isResource);
}
public static String read(String path, String charset, boolean isResource) throws IOException {
return read(pathToUrl(path, isResource), charset);
}
@SuppressWarnings("resource")
public static String read(URL url, String charset) throws IOException {
return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
}
}
Extra
Hier is de volledige code voor het voorbeeld van Dheeraj Sachan.
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
public class JsonHandler {
private static ObjectMapper propertyMapper;
static {
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
propertyMapper = new ObjectMapper();
propertyMapper.setDateFormat(df);
propertyMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
propertyMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
propertyMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
}
private static class MyHashMap extends HashMap<String, List<Video>>{
private static final long serialVersionUID = 7023107716981734468L;
}
private static class Video implements Serializable {
private static final long serialVersionUID = -446275421030765463L;
private String dashUrl;
private String videoBitrate;
private String audioBitrate;
private int videoWidth;
private int videoHeight;
private long fileSize;
@Override
public String toString() {
return "Video [url=" + dashUrl + ", video=" + videoBitrate + ", audio=" + audioBitrate
+ ", width=" + videoWidth + ", height=" + videoHeight + ", size=" + fileSize + "]";
}
}
public static void main(String[] args) {
try {
HashMap<String, List<Video>> map = loadJson("sample.json", true);
Iterator<Entry<String, List<Video>>> lectures = map.entrySet().iterator();
while (lectures.hasNext()) {
Entry<String, List<Video>> lecture = lectures.next();
System.out.printf("Lecture #%s%n", lecture.getKey());
for (Video video : lecture.getValue()) {
System.out.println(video);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static <T> T parseUnderScoredResponse(String json, Class<T> classOfT) {
try {
if (json == null) {
return null;
}
return propertyMapper.readValue(json, classOfT);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
if (isResource) {
return JsonHandler.class.getClassLoader().getResource(path);
}
return new URL("file:/" + path);
}
public static File load(String path, boolean isResource) throws MalformedURLException {
return load(pathToUrl(path, isResource));
}
public static File load(URL url) {
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
return new File(url.getPath());
}
}
@SuppressWarnings("resource")
public static String readFile(URL url, String charset) throws IOException {
return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
}
public static String loadJsonString(String path, boolean isResource) throws IOException {
return readFile(path, isResource, "UTF-8");
}
public static String readFile(String path, boolean isResource, String charset) throws IOException {
return readFile(pathToUrl(path, isResource), charset);
}
public static HashMap<String, List<Video>> loadJson(String jsonString) throws IOException {
return JsonHandler.parseUnderScoredResponse(jsonString, MyHashMap.class);
}
public static HashMap<String, List<Video>> loadJson(String path, boolean isResource) throws IOException {
return loadJson(loadJsonString(path, isResource));
}
}