简体   繁体   English

将JSON字符串转换为JSON对象

[英]Convert JSON string to json objects

I have a json string returning: 我有一个返回的json字符串:

[{"TRAIN_JOURNEY_STAFF[],"ID":15,"EMAIL_ADDRESS":"jk@connectedrail.com","PASSWORD":"test","FIRST_NAME":"Joe","LAST_NAME":"Kevin","DATE_OF_BIRTH":"1996-04-20T00:00:00","GENDER":"Male","STAFF_ROLE":"Conductor","PHOTO":null},{new record..}]

There are several records here, I can't find a way to convert this json string to individual objects. 这里有几条记录,我找不到将这个json字符串转换为单个对象的方法。 I'm using the following to read in the data: 我正在使用以下内容读取数据:

StringBuffer response;
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()))) {
        String inputLine;
        response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
    }
    System.out.print(response.toString());
}

I've tried the simple json libary but the parser mixes up the string, Which is not ideal as I need to output the data to rows object by object to jtables. 我已经尝试过简单的json库,但是解析器将字符串混合在一起,这并不理想,因为我需要将数据逐行输出到jtables。

Any help would be appreciated. 任何帮助,将不胜感激。

Solved it with the below with GSON. 使用GSON在下面解决了该问题。 Many thanks everyone! 非常感谢大家!

    JsonElement jelement = new JsonParser().parse(response.toString());
    JsonArray jarray = jelement.getAsJsonArray();

    JsonObject jobject = jarray.get(0).getAsJsonObject();

    System.out.println(jobject.get("FIRST_NAME"));

You can use something like this: 您可以使用如下形式:

public class ObjectSerializer {

private static ObjectMapper objectMapper;

@Autowired
public ObjectSerializer(ObjectMapper objectMapper) {
    ObjectSerializer.objectMapper = objectMapper;
}

public static <T> T getObject(Object obj, Class<T> class1) {
    String jsonObj = "";
    T userDto = null;
    try {
        jsonObj = objectMapper.writeValueAsString(obj);
        userDto = (T) objectMapper.readValue(jsonObj, class1);
        System.out.println(jsonObj);
    } catch (JsonProcessingException jpe) {
    } catch (IOException e) {
        e.printStackTrace();
    }
    return userDto;
}

Pass your JSON Object to this method alogn with class name and it will set the JSON data to that respective class. 将您的JSON对象传递给带有类名的此方法alogn,它将把JSON数据设置为相应的类。

Note: Class must have the same variables as in the JSON that you want to map with it. 注意:类必须具有与要与其映射的JSON中相同的变量。

What you have basically is this : 你基本上是这样的:

[
  {
  "TRAIN_JOURNEY_STAFF":[
  ],
  "ID":15,
  "EMAIL_ADDRESS":"jk@connectedrail.com",
  "PASSWORD":"test",
  "FIRST_NAME":"Joe",
  "LAST_NAME":"Kevin",
  "DATE_OF_BIRTH":"1996-04-20T00:00:00",
  "GENDER":"Male",
  "STAFF_ROLE":"Conductor",
  "PHOTO":null
  },
  {

  }
]

You can use JSON constructor to serialize this array to an Array of JSONObjects . 您可以使用JSON构造函数将此数组序列化为JSONObjects数组。 Try looking for JSONObject and JSONArray classes in Java. 尝试在Java中寻找JSONObjectJSONArray类。 The constructor basically takes the stringified JSON (which you already have). 构造函数基本上采用字符串化的JSON(您已经拥有)。

Using org.json library: 使用org.json库:

JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");

see this 看到这个

You can use Jackson to convert JSON to an object.Include the dependency : 您可以使用Jackson将JSON转换为对象,包括依赖项:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

Then make a POJO class to store the JSON .The pojo class should reflect the json string structure and should have appropriate fields to map the values(Here in sample code Staff.class is a pojo class).Then, by using ObjectMapper class you can convert the JSON string to a java object as follows : 然后创建一个POJO类以存储JSON.pojo类应反映json字符串结构,并应具有适当的字段以映射值(此处示例代码Staff.class是pojo类)。然后,使用ObjectMapper类可以如下将JSON字符串转换为java对象:

StringBuffer response;
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()))) {
        String inputLine;
        response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
    }
    System.out.print(response.toString());

  ObjectMapper mapper = new ObjectMapper();

  //JSON from file to Object
  Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);

  //JSON from String to Object 
  Staff obj = mapper.readValue(response.toString(), Staff.class);

Another simple method to read a JSON string and convert it into an object is : 读取JSON字符串并将其转换为对象的另一种简单方法是:

JSON String: JSON字符串:

{
     "lastName":"Smith",
    "address":{
        "streetAddress":"21 2nd Street",
         "city":"New York",
         "state":"NY",
         "postalCode":10021
    },
     "age":25,
     "phoneNumbers":[
            {
            "type":"home", "number":"212 555-1234"
            },
         {
            "type":"fax", "number":"212 555-1234"
         }
     ],
     "firstName":"John"
}

public class JSONReadExample  
{ 
    public static void main(String[] args) throws Exception  
    { 
        // parsing file "JSONExample.json" 
        Object obj = new JSONParser().parse(new FileReader("JSONExample.json")); 

        // typecasting obj to JSONObject 
        JSONObject jo = (JSONObject) obj; 

        // getting firstName and lastName 
        String firstName = (String) jo.get("firstName"); 
        String lastName = (String) jo.get("lastName"); 

        System.out.println(firstName); 
        System.out.println(lastName); 

        // getting age 
        long age = (long) jo.get("age"); 
        System.out.println(age); 

        // getting address 
        Map address = ((Map)jo.get("address")); 

        // iterating address Map 
        Iterator<Map.Entry> itr1 = address.entrySet().iterator(); 
        while (itr1.hasNext()) { 
            Map.Entry pair = itr1.next(); 
            System.out.println(pair.getKey() + " : " + pair.getValue()); 
        } 

        // getting phoneNumbers 
        JSONArray ja = (JSONArray) jo.get("phoneNumbers"); 

        // iterating phoneNumbers 
        Iterator itr2 = ja.iterator(); 

        while (itr2.hasNext())  
        { 
            itr1 = ((Map) itr2.next()).entrySet().iterator(); 
            while (itr1.hasNext()) { 
                Map.Entry pair = itr1.next(); 
                System.out.println(pair.getKey() + " : " + pair.getValue()); 
            } 
        } 
    } 
} 

For reference: 以供参考:
https://www.geeksforgeeks.org/parse-json-java/ https://www.geeksforgeeks.org/parse-json-java/
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/ https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/

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

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