简体   繁体   English

如何解析JSON字符串并填充包含Map的对象?

[英]How to parse JSON string and populate an object containing Map?

I have for example this JSON string: 例如,我有以下JSON字符串:

{"name":"Nataraj", "job":"Programmer","property":["chair":"my","table":"brothers","cabinet":"mothers"]}

and, i want to get this data to class as: 而且,我想将此数据归类为:

public class A{
  String name;
  String job;
  //Map<String, String> property; (Maybe: <String, Object>?)
}

How do I get the data to this map? 如何将数据获取到此地图? The main problem I have with "property". 我的主要问题是“财产”。 I used JSONObject and ObjectMapper, but on the property i have problem. 我使用了JSONObject和ObjectMapper,但是在属性上我遇到了问题。 Of course, every variable in class A has getter and setter. 当然,A类中的每个变量都有getter和setter。 Any help for me? 对我有帮助吗?

First of all your JSON has to be modified a bit. 首先,您的JSON必须进行一些修改。 The property is not an Array rather an Object containing key-value pairs. property不是Array而是包含键值对的Object It should be like this: 应该是这样的:

{"name":"Nataraj", "job":"Programmer","property":
{"chair":"my","table":"brothers","cabinet":"mothers"}}

As I mentioned in the comment to original post, you may use org.json:json library or Jackson or Gson library to parse any JSON string and populate your objects. 正如我在原始帖子的评论中提到的那样,您可以使用org.json:json库或JacksonGson库来解析任何JSON字符串并填充对象。

Here is the executable program that parses your JSON using basic org.json:json library and populates the data structure you expect: 这是使用基本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 +
                    '}';
        }
    }
}

You should add Maven (or equivalent Gradle or other) dependency to: 您应该将Maven (或等效的Gradle或其他)依赖项添加到:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

The following works just fine with Gson 2.8.5 : 以下在Gson 2.8.5上可以正常工作:

A instance = new Gson().fromJson(data, A.class)

The full class for you to try : 完整课程供您尝试:

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);
        }
    }
}

Most other JSON parsing libraries provide similar functionality. 大多数其他JSON解析库都提供类似的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM