![](/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.