Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2445153
  • 博文数量: 328
  • 博客积分: 4302
  • 博客等级: 上校
  • 技术积分: 5486
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-01 11:14
个人简介

悲剧,绝对的悲剧,悲剧中的悲剧。

文章分类

全部博文(328)

文章存档

2017年(6)

2016年(18)

2015年(28)

2014年(73)

2013年(62)

2012年(58)

2011年(55)

2010年(28)

分类: Java

2015-07-13 16:27:14

javax.json 没有提供直接的判断某个键是否存在的方法,需要自己来实现,只能通过查看所有key的list

  1. import java.util.Arrays;

  2. // 打印所有key的列表
  3. for (String key: jsonObject.keySet()) {
  4.     System.out.println(key);
  5. }

  6. // 把set转换成array
  7. //String[] keys = jsonObject.keySet().toArray(myset.size());
  8. String[] keys = jsonObject.keySet().toArray(new String[0]);

  9. // 进行判断
  10. if (Arrays.asList(keys).contains("datestring")){
  11.     System.out.println("Yes");
  12. } else {
  13.     System.out.println("No");
  14. }




JSON (JavaScript Object Notation) is text-based lightweight technology for generating human readable formatted data. JSON represent object data in the form of key-value pairs. We can have nested JSON objects too and it provides an easy way to represent arrays also.
JSON is widely used in web applications or as server response because it’s lightweight and more compact than XML. JSON objects are easy to read and write and most of the technologies provide support for JSON objects.

JSR353 finally made into Java EE 7 and it’s the Java API for JSON processing. jsonp is the reference implementation for JSON Processing API. We can use this in maven project by adding following dependency.
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.0.2</version>
</dependency>
If you are using GlassFish 4.0 then you can keep the scope as provided because it’s already included in the server.

JSON API provides two ways for JSON processing:

  1. Object Model API – It’s similar to DOM Parser and good for small objects.
  2. Streaming API – It’s similar to StaX Parser and good for large objects where you don’t want to keep whole object in memory.

Some important interfaces of JSON API are:
  1. javax.json.JsonReader: We can use this to read JSON object or an array to JsonObject. We can get JsonReader from Json class or JsonReaderFactory.
  2. javax.json.JsonWriter: We can use this to write JSON object to output stream.
  3. javax.json.stream.JsonParser: This works as a pull parser and provide streaming support for reading JSON objects.
  4. javax.json.stream.JsonGenerator: We can use this to write JSON object to output source in streaming way.
  5. javax.json.Json: This is the factory class for creating JSON processing objects. This class provides the most commonly used methods for creating these objects and their corresponding factories. The factory classes provide all the various ways to create these objects.
  6. javax.json.JsonObject: JsonObject represents an immutable JSON object value.

Let’s look into the usage of JSON API with simple program, we have a JSON object stored in a file as:


employee.txt
{
    "id":123,
    "name":"Pankaj Kumar",
    "permanent":true,
    "address":{
            "street":"El Camino Real",
            "city":"San Jose",
            "zipcode":95014
        },
    "phoneNumbers":[9988664422, 1234567890],
    "role":"Developer"
}
We have java bean classes that represent above JSON format as:

Employee.java
package com.journaldev.model;
 
import java.util.Arrays;
 
public class Employee {
 
    private int id;
    private String name;
    private boolean permanent;
    private Address address;
    private long[] phoneNumbers;
    private String role;
     
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public boolean isPermanent() {
        return permanent;
    }
    public void setPermanent(boolean permanent) {
        this.permanent = permanent;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public long[] getPhoneNumbers() {
        return phoneNumbers;
    }
    public void setPhoneNumbers(long[] phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
     
    @Override
    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("***** Employee Details *****\n");
        sb.append("ID="+getId()+"\n");
        sb.append("Name="+getName()+"\n");
        sb.append("Permanent="+isPermanent()+"\n");
        sb.append("Role="+getRole()+"\n");
        sb.append("Phone Numbers="+Arrays.toString(getPhoneNumbers())+"\n");
        sb.append("Address="+getAddress());
        sb.append("\n*****************************");
         
        return sb.toString();
    }
}
Address.java
package com.journaldev.model;
 
public class Address {
     
    private String street;
    private String city;
    private int zipcode;
     
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public int getZipcode() {
        return zipcode;
    }
    public void setZipcode(int zipcode) {
        this.zipcode = zipcode;
    }
     
    @Override
    public String toString(){
        return getStreet() + ", "+getCity()+", "+getZipcode();
    }
}
I have overridden the toString() method to return human readable String representation that we will use in our JSON implementation classes.


JsonReader Example



EmployeeJSONReader.java
package com.journaldev.json;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
 
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
 
import com.journaldev.model.Address;
import com.journaldev.model.Employee;
 
public class EmployeeJSONReader {
 
    public static final String JSON_FILE="employee.txt";
     
    public static void main(String[] args) throws IOException {
        InputStream fis = new FileInputStream(JSON_FILE);
         
        //create JsonReader object
        JsonReader jsonReader = Json.createReader(fis);
         
        /**
         * We can create JsonReader from Factory also
        JsonReaderFactory factory = Json.createReaderFactory(null);
        jsonReader = factory.createReader(fis);
        */
         
        //get JsonObject from JsonReader
        JsonObject jsonObject = jsonReader.readObject();
         
        //we can close IO resource and JsonReader now
        jsonReader.close();
        fis.close();
         
        //Retrieve data from JsonObject and create Employee bean
        Employee emp = new Employee();
         
        emp.setId(jsonObject.getInt("id"));
        emp.setName(jsonObject.getString("name"));
        emp.setPermanent(jsonObject.getBoolean("permanent"));
        emp.setRole(jsonObject.getString("role"));
         
        //reading arrays from json
        JsonArray jsonArray = jsonObject.getJsonArray("phoneNumbers");
        long[] numbers = new long[jsonArray.size()];
        int index = 0;
        for(JsonValue value : jsonArray){
            numbers[index++] = Long.parseLong(value.toString());
        }
        emp.setPhoneNumbers(numbers);
         
        //reading inner object from json object
        JsonObject innerJsonObject = jsonObject.getJsonObject("address");
        Address address = new Address();
        address.setStreet(innerJsonObject.getString("street"));
        address.setCity(innerJsonObject.getString("city"));
        address.setZipcode(innerJsonObject.getInt("zipcode"));
        emp.setAddress(address);
         
        //print employee bean information
        System.out.println(emp);
         
    }
 
}
The implementation is straight forward and feels similar as getting parameters from HashMap. JsonReaderFactory implements Factory Design Pattern. Once we execute above program, we get following output.


***** Employee Details *****
ID=123
Name=Pankaj Kumar
Permanent=true
Role=Developer
Phone Numbers=[9988664422, 1234567890]
Address=El Camino Real, San Jose, 95014
*****************************

JsonWriter Example


EmployeeJsonWriter.java
package com.journaldev.json;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
 
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
 
import com.journaldev.model.Address;
import com.journaldev.model.Employee;
 
public class EmployeeJSONWriter {
 
    public static void main(String[] args) throws FileNotFoundException {
 
        Employee emp = createEmployee();
 
        JsonObjectBuilder empBuilder = Json.createObjectBuilder();
        JsonObjectBuilder addressBuilder = Json.createObjectBuilder();
        JsonArrayBuilder phoneNumBuilder = Json.createArrayBuilder();
 
        for (long phone : emp.getPhoneNumbers()) {
            phoneNumBuilder.add(phone);
        }
         
        addressBuilder.add("street", emp.getAddress().getStreet())
                        .add("city", emp.getAddress().getCity())
                            .add("zipcode", emp.getAddress().getZipcode());
         
        empBuilder.add("id", emp.getId())
                    .add("name", emp.getName())
                        .add("permanent", emp.isPermanent())
                            .add("role", emp.getRole());
         
        empBuilder.add("phoneNumbers", phoneNumBuilder);
        empBuilder.add("address", addressBuilder);
         
        JsonObject empJsonObject = empBuilder.build();
         
        System.out.println("Employee JSON String\n"+empJsonObject);
         
        //write to file
        OutputStream os = new FileOutputStream("emp.txt");
        JsonWriter jsonWriter = Json.createWriter(os);
        /**
         * We can get JsonWriter from JsonWriterFactory also
        JsonWriterFactory factory = Json.createWriterFactory(null);
        jsonWriter = factory.createWriter(os);
        */
        jsonWriter.writeObject(empJsonObject);
        jsonWriter.close();
    }
     
 
    public static Employee createEmployee() {
 
        Employee emp = new Employee();
        emp.setId(100);
        emp.setName("David");
        emp.setPermanent(false);
        emp.setPhoneNumbers(new long[] { 123456, 987654 });
        emp.setRole("Manager");
 
        Address add = new Address();
        add.setCity("Bangalore");
        add.setStreet("BTM 1st Stage");
        add.setZipcode(560100);
        emp.setAddress(add);
 
        return emp;
    }
 
}
Once we run above application, we get following response:

Employee JSON String
{"id":100,"name":"David","permanent":false,"role":"Manager","phoneNumbers":[123456,987654],"address":{"street":"BTM 1st Stage","city":"Bangalore","zipcode":560100}}
JSON object is also getting saved in emp.txt file. JsonObjectBuilder implements builder pattern that makes it very easy to use.

JsonParser Example


JsonParser is a pull parser and we read the next element with next() method that returns an Event object.javax.json.stream.JsonParser.Event is an Enum that makes it type-safe and easy to use. We can use in switch case to set our java bean properties.


EmployeeJSONParser.java
package com.journaldev.json;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
 
import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;
 
import com.journaldev.model.Address;
import com.journaldev.model.Employee;
 
public class EmployeeJSONParser {
 
    public static final String FILE_NAME = "employee.txt";
 
    public static void main(String[] args) throws IOException {
        InputStream fis = new FileInputStream(FILE_NAME);
 
        JsonParser jsonParser = Json.createParser(fis);
 
        /**
         * We can create JsonParser from JsonParserFactory also with below code
         * JsonParserFactory factory = Json.createParserFactory(null);
         * jsonParser = factory.createParser(fis);
         */
 
        Employee emp = new Employee();
        Address address = new Address();
        String keyName = null;
        List<Long> phoneNums = new ArrayList<Long>();
         
        while (jsonParser.hasNext()) {
            Event event = jsonParser.next();
            switch (event) {
            case KEY_NAME:
                keyName = jsonParser.getString();
                break;
            case VALUE_STRING:
                setStringValues(emp, address, keyName, jsonParser.getString());
                break;
            case VALUE_NUMBER:
                setNumberValues(emp, address, keyName, jsonParser.getLong(), phoneNums);
                break;
            case VALUE_FALSE:
                setBooleanValues(emp, address, keyName, false);
                break;
            case VALUE_TRUE:
                setBooleanValues(emp, address, keyName, true);
                break;
            case VALUE_NULL:
                // don't set anything
                break;
            default:
                // we are not looking for other events
            }
        }
        emp.setAddress(address);
        long[] nums = new long[phoneNums.size()];
        int index = 0;
        for(Long l :phoneNums){
            nums[index++] = l;
        }
        emp.setPhoneNumbers(nums);
         
        System.out.println(emp);
         
        //close resources
        fis.close();
        jsonParser.close();
    }
 
    private static void setNumberValues(Employee emp, Address address,
            String keyName, long value, List<Long> phoneNums) {
        switch(keyName){
        case "zipcode":
            address.setZipcode((int)value);
            break;
        case "id":
            emp.setId((int) value);
            break;
        case "phoneNumbers":
            phoneNums.add(value);
            break;
        default:
            System.out.println("Unknown element with key="+keyName);    
        }
    }
 
    private static void setBooleanValues(Employee emp, Address address,
            String key, boolean value) {
        if("permanent".equals(key)){
            emp.setPermanent(value);
        }else{
            System.out.println("Unknown element with key="+key);
        }
    }
 
    private static void setStringValues(Employee emp, Address address,
            String key, String value) {
        switch(key){
        case "name":
            emp.setName(value);
            break;
        case "role":
            emp.setRole(value);
            break;
        case "city":
            address.setCity(value);
            break;
        case "street":
            address.setStreet(value);
            break;
        default:
            System.out.println("Unknown Key="+key);
                 
        }
    }
 
}
The major complexity comes when we need to write the logic to parse the data and sometimes it can get complex.


Since we are reading the same file as JsonReader, the output is same as EmployeeJsonReader program.

JsonGenerator Example


EmployeeJsonGenerator.java
package com.journaldev.json;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
 
import javax.json.Json;
import javax.json.stream.JsonGenerator;
 
import com.journaldev.model.Employee;
 
public class EmployeeJSONGenerator {
 
    public static void main(String[] args) throws IOException {
        OutputStream fos = new FileOutputStream("emp_stream.txt");
        JsonGenerator jsonGenerator = Json.createGenerator(fos);
        /**
         * We can get JsonGenerator from Factory class also
         * JsonGeneratorFactory factory = Json.createGeneratorFactory(null);
         * jsonGenerator = factory.createGenerator(fos);
         */
         
        Employee emp = EmployeeJSONWriter.createEmployee();
        jsonGenerator.writeStartObject(); // {
        jsonGenerator.write("id", emp.getId()); // "id":123
        jsonGenerator.write("name", emp.getName());
        jsonGenerator.write("role", emp.getRole());
        jsonGenerator.write("permanent", emp.isPermanent());
         
        jsonGenerator.writeStartObject("address") //start of address object
            .write("street", emp.getAddress().getStreet())
            .write("city",emp.getAddress().getCity())
            .write("zipcode",emp.getAddress().getZipcode())
            .writeEnd(); //end of address object
         
        jsonGenerator.writeStartArray("phoneNumbers"); //start of phone num array
        for(long num : emp.getPhoneNumbers()){
            jsonGenerator.write(num);
        }
        jsonGenerator.writeEnd(); // end of phone num array
        jsonGenerator.writeEnd(); // }
         
        jsonGenerator.close();
         
    }
 
}
JsonGenerator is very easy to use and provides good performance for large data.


That’s all for Java API for JSON Processing, you can download java project from below link and play around with it.

References:
JSONLint – Great web tool to validate JSON data
JSON Processing Reference Implementation
JSR353 JCP Page

转载自:http://www.journaldev.com/2315/java-json-processing-api-example-tutorial

阅读(3057) | 评论(0) | 转发(0) |
0

上一篇:Python Pexpect 的使用

下一篇:Java 反射

给主人留下些什么吧!~~