转换JSON代码的最佳方法是什么:
{
"data" :
{
"field1" : "value1",
"field2" : "value2"
}
}
在Java Map中,其中一个键是(field1, field2),这些字段的值是(value1, value2)。
什么好主意吗?我应该使用Json-lib吗?或者如果我自己编写解析器会更好?
转换JSON代码的最佳方法是什么:
{
"data" :
{
"field1" : "value1",
"field2" : "value2"
}
}
在Java Map中,其中一个键是(field1, field2),这些字段的值是(value1, value2)。
什么好主意吗?我应该使用Json-lib吗?或者如果我自己编写解析器会更好?
当前回答
试试下面的代码:
public static Map<String, Object> convertJsonIntoMap(String jsonFile) {
Map<String, Object> map = new HashMap<>();
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.readValue(jsonFile, new TypeReference<Map<String, Object>>() {
});
map = mapper.readValue(jsonFile, new TypeReference<Map<String, String>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
其他回答
我这样做。这很简单。
import java.util.Map;
import org.json.JSONObject;
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
JSONObject jsonObj = new JSONObject("{ \"f1\":\"v1\"}");
@SuppressWarnings("unchecked")
Map<String, String> map = new Gson().fromJson(jsonObj.toString(),Map.class);
System.out.println(map);
}
}
java.lang.reflect.Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Gson gson = new Gson();
Map<String, Object> categoryicons = gson.fromJson(json, mapType );
试试这段代码,对我很管用,
Map<String, Object> retMap = new Gson().fromJson(
myJsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);
试试下面的代码:
public static Map<String, Object> convertJsonIntoMap(String jsonFile) {
Map<String, Object> map = new HashMap<>();
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.readValue(jsonFile, new TypeReference<Map<String, Object>>() {
});
map = mapper.readValue(jsonFile, new TypeReference<Map<String, String>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
import net.sf.json.JSONObject
JSONObject.fromObject(yourJsonString).toMap