![](/img/trans.png)
[英]Java Parse Json Object Containing Map of Strings to Map to Strings to a String Array
[英]How to parse JSON string and populate an object containing Map?
例如,我有以下JSON字符串:
{"name":"Nataraj", "job":"Programmer","property":["chair":"my","table":"brothers","cabinet":"mothers"]}
而且,我想將此數據歸類為:
public class A{
String name;
String job;
//Map<String, String> property; (Maybe: <String, Object>?)
}
如何將數據獲取到此地圖? 我的主要問題是“財產”。 我使用了JSONObject和ObjectMapper,但是在屬性上我遇到了問題。 當然,A類中的每個變量都有getter和setter。 對我有幫助嗎?
首先,您的JSON
必須進行一些修改。 該property
不是Array
而是包含鍵值對的Object
。 應該是這樣的:
{"name":"Nataraj", "job":"Programmer","property":
{"chair":"my","table":"brothers","cabinet":"mothers"}}
正如我在原始帖子的評論中提到的那樣,您可以使用org.json:json
庫或Jackson
或Gson
庫來解析任何JSON
字符串並填充對象。
這是使用基本org.json:json
庫解析JSON
並填充您期望的數據結構的可執行程序:
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class ParseJsonIntoMap {
public static void main(String[] args) {
String data="{\"name\":\"Nataraj\", \"job\":\"Programmer\",\"property\":{\"chair\":\"my\",\"table\":\"brothers\",\"cabinet\":\"mothers\"}}";
JSONObject parsedData = new JSONObject(data);
A a = new A();
a.setName(parsedData.getString("name"));
a.setJob(parsedData.getString("job"));
JSONObject propertyMap = parsedData.getJSONObject("property");
for (String key : propertyMap.keySet()) {
a.getProperty().put(key, propertyMap.getString(key));
}
System.out.println("Output: "+a);
}
public static class A{
String name;
String job;
Map<String, String> property = new HashMap<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Map<String, String> getProperty() {
return property;
}
public void setProperty(Map<String, String> property) {
this.property = property;
}
@Override
public String toString() {
return "A{" +
"name='" + name + '\'' +
", job='" + job + '\'' +
", property=" + property +
'}';
}
}
}
您應該將Maven
(或等效的Gradle或其他)依賴項添加到:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
以下在Gson 2.8.5上可以正常工作:
A instance = new Gson().fromJson(data, A.class)
完整課程供您嘗試:
import java.util.Map;
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
String data="{\"name\":\"Nataraj\", \"job\":\"Programmer\",\"property\":{\"chair\":\"my\",\"table\":\"brothers\",\"cabinet\":\"mothers\"}}";
System.out.println(new Gson().fromJson(data, A.class));
}
static class A{
String name;
String job;
Map<String, String> property;
@Override
public String toString() { // just there for the System.out.println in main
return String.format("name: %s, job: %s, property: %s", name, job, property);
}
}
}
大多數其他JSON解析庫都提供類似的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.