Java Code Examples for javax.json.Json#createParser()

The following examples show how to use javax.json.Json#createParser() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public QueryMessage decode(String s) throws DecodeException {
    MultivaluedMapImpl<String,String> map = new MultivaluedMapImpl<>();
    try (JsonParser parser = Json.createParser(new StringReader(s))) {
        while (parser.hasNext()) {
            if (parser.next() == JsonParser.Event.KEY_NAME) {
                String key = parser.getString();
                addValueToMap(key, parser, map);
            }
        }
    }
    if (map.size() == 1 && map.containsKey("cancel"))
        return new CancelMessage();
    else
        return new CreateQueryMessage(map);
}
 
Example 2
Source Project: webex-java-sdk   File: Client.java    License: MIT License 6 votes vote down vote up
public <T> LinkedResponse<List<T>> paginate(final Class<T> clazz, URL url) {
    LinkedResponse.BodyCreator<List<T>> function = new LinkedResponse.BodyCreator<List<T>>() {
        @Override
        public List<T> create(InputStream istream) {
            JsonParser parser = Json.createParser(istream);
            Client.this.scrollToItemsArray(parser);

            List<T> result = new ArrayList<T>();
            for (JsonParser.Event event = parser.next();
                 event == JsonParser.Event.START_OBJECT;
                 event = parser.next()) {
                result.add(readObject(clazz, parser));
            }
            return result;
        }
    };

    try {
        return new LinkedResponse<List<T>>(this, url, function);
    } catch (IOException e) {
        throw new SparkException("io error", e);
    }
}
 
Example 3
Source Project: tomee   File: WeatherServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
private List<JsonItem> convertToMap(String s) {
    JsonParser expectedParser = Json.createParser(new StringReader(s));
    List<JsonItem> list = new ArrayList<>();
    while (expectedParser.hasNext()) {
        JsonParser.Event event = expectedParser.next();
        switch (event) {
            case KEY_NAME:
            case VALUE_STRING:
            case VALUE_NUMBER:
                list.add(new JsonItem(event, expectedParser.getValue().toString()));
                break;
            default:
                list.add(new JsonItem(event));
        }
    }
    return list;
}
 
Example 4
Source Project: javaee7-websocket   File: MessageDecoder.java    License: MIT License 6 votes vote down vote up
@Override
public boolean willDecode(String string) {
    boolean decodes = false;
    /* Convert the message into a map */
    messageMap = new HashMap<>();
    JsonParser parser = Json.createParser(new StringReader(string));
    while (parser.hasNext()) {
        if (parser.next() == JsonParser.Event.KEY_NAME) {
            String key = parser.getString();
            parser.next();
            String value = parser.getString();
            messageMap.put(key, value);
        }
    }
    /* Check the kind of message and if all fields are included */
    Set keys = messageMap.keySet();
    if (keys.contains("type")) {
        switch (messageMap.get("type")) {
            case "betMatchWinner":
                if (keys.contains("name"))
                    decodes = true;
                break;
        }
    }
    return decodes;
}
 
Example 5
private void assertComplexMetricValue(CamelContext camelctx, String metricName, Number metricValue) throws Exception {
    String metrics = getMetrics();

    JsonParser parser = Json.createParser(new StringReader(metrics));
    Assert.assertTrue("Metrics endpoint content is empty", parser.hasNext());
    parser.next();

    JsonObject jsonObject = parser.getObject();
    JsonNumber result = null;
    String[] nameParts = metricName.split("\\.");
    for (int i = 0; i < nameParts.length; i++) {
        String jsonKey = i + 1 == nameParts.length ? nameParts[i] + ";camelContext=" + camelctx.getName() : nameParts[i];

        if (i + 1 == nameParts.length) {
            result = jsonObject.getJsonNumber(jsonKey);
            break;
        } else {
            jsonObject = jsonObject.getJsonObject(jsonKey);
        }
    }

    Assert.assertNotNull("Expected to find metric " + metricName, result);
    Assert.assertEquals("Expected metric " + metricName + " to have value " + metricValue, metricValue, result.intValue());
}
 
Example 6
public Map<String, String> getProperties() {
    Map<String, String> m = new HashMap<String, String>();
    String jsonData = this.readFile(this.fileLocation);
    JsonParser parser = Json.createParser(new StringReader(jsonData));
    String key = null;
    while (parser.hasNext()) {
        final Event event = parser.next();
        switch (event) {
        case KEY_NAME:
            key = parser.getString();
            break;
        case VALUE_STRING:
            String string = parser.getString();
            m.put(key, string);
            break;
        case VALUE_NUMBER:
            BigDecimal number = parser.getBigDecimal();
            m.put(key, number.toString());
            break;
        case VALUE_TRUE:
            m.put(key, "true");
            break;
        case VALUE_FALSE:
            m.put(key, "false");
            break;
        default:
            break;
        }
    }
    parser.close();
    return m;
}
 
Example 7
public Map<String, String> getProperties() {
    Map<String, String> m = new HashMap<String, String>();
    String jsonData = this.readFile(this.fileLocation);
    JsonParser parser = Json.createParser(new StringReader(jsonData));
    String key = null;
    while (parser.hasNext()) {
        final Event event = parser.next();
        switch (event) {
        case KEY_NAME:
            key = parser.getString();
            break;
        case VALUE_STRING:
            String string = parser.getString();
            m.put(key, string);
            break;
        case VALUE_NUMBER:
            BigDecimal number = parser.getBigDecimal();
            m.put(key, number.toString());
            break;
        case VALUE_TRUE:
            m.put(key, "true");
            break;
        case VALUE_FALSE:
            m.put(key, "false");
            break;
        default:
            break;
        }
    }
    parser.close();
    return m;
}
 
Example 8
public Map<String, String> getProperties() {
    Map<String, String> m = new HashMap<String, String>();
    String jsonData = this.readFile(this.fileLocation);
    JsonParser parser = Json.createParser(new StringReader(jsonData));
    String key = null;
    while (parser.hasNext()) {
        final Event event = parser.next();
        switch (event) {
        case KEY_NAME:
            key = parser.getString();
            break;
        case VALUE_STRING:
            String string = parser.getString();
            m.put(key, string);
            break;
        case VALUE_NUMBER:
            BigDecimal number = parser.getBigDecimal();
            m.put(key, number.toString());
            break;
        case VALUE_TRUE:
            m.put(key, "true");
            break;
        case VALUE_FALSE:
            m.put(key, "false");
            break;
        default:
            break;
        }
    }
    parser.close();
    return m;
}
 
Example 9
Source Project: ee8-sandbox   File: JsonpTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonParser() {
    String key = "";
    String value = "";
    JsonParser parser = Json.createParser(JsonpTest.class.getResourceAsStream("/person.json"));
    while (parser.hasNext()) {
        JsonParser.Event e = parser.next();
        System.out.print(e.name());

        switch (e) {
            case START_ARRAY:
                if (key.equals("phoneNumbers")) {
                    parser.skipArray();
                }
                break;
            case KEY_NAME:
                key = parser.getString();
                System.out.print(" - " + parser.getString());
                break;
            case VALUE_STRING:
                System.out.print(" - " + parser.getString());
                if ("name".equals(key)) {
                    value = parser.getString();
                }
        }

        System.out.println();
    }

    assertEquals("Duke", value);
}
 
Example 10
Source Project: sample.daytrader7   File: ActionMessage.java    License: Apache License 2.0 5 votes vote down vote up
public void doDecoding(String jsonText) {
          
    String keyName = null;
    try 
    {
        // JSON parse
        JsonParser parser = Json.createParser(new StringReader(jsonText));
        while (parser.hasNext()) {
            JsonParser.Event event = parser.next();
            switch(event) {
            case KEY_NAME:
                keyName=parser.getString();
                break;
            case VALUE_STRING:
                if (keyName != null && keyName.equals("action")) {
                    decodedAction=parser.getString();
                }
                break;
            default:
                break;
            }
        }
    } catch (Exception e) {
        Log.error("ActionMessage:doDecoding(" + jsonText + ") --> failed", e);
    }
    
    if (Log.doTrace()) {
        if (decodedAction != null ) {
            Log.trace("ActionMessage:doDecoding -- decoded action -->" + decodedAction + "<--");
        } else {
            Log.trace("ActionMessage:doDecoding -- decoded action -->null<--");
        }
    }
    
}
 
Example 11
Source Project: tutorials   File: JsonUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenUsingStreamingApiToQueryForSpecificProperty_thenExpectedValueIsReturned(
        ) throws IOException, ParseException {
    JsonParser jsonParser = Json.createParser(new StringReader(petshopJson));
    
    int count = 0;
    String result = null;
    
    while(jsonParser.hasNext()) {
        Event e = jsonParser.next();
        
        if (e == Event.KEY_NAME) {
            if(jsonParser.getString().equals("name")) {
               jsonParser.next();
               
               if(++count == 3) {
                   result = jsonParser.getString();
                   break;
               }
            }   
        }
    }
    
    assertEquals(
            "The query should return the 'name' property of the third pet from the list", 
            "Jake", 
            result);
}
 
Example 12
private void assertSimpleMetricValue(CamelContext camelctx, String metricName, Number metricValue) throws Exception {
    String metrics = getMetrics();

    JsonParser parser = Json.createParser(new StringReader(metrics));
    Assert.assertTrue("Metrics endpoint content is empty", parser.hasNext());
    parser.next();

    JsonNumber jsonNumber = parser.getObject().getJsonNumber(metricName + ";camelContext=" + camelctx.getName());

    Assert.assertEquals("Expected to find metric" + metricName + " with value " + metricValue, metricValue, jsonNumber.intValue());
}
 
Example 13
Source Project: journaldev   File: EmployeeJSONParser.java    License: MIT License 4 votes vote down vote up
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();
}
 
Example 14
public static Data fromJSON(String string) {
	try (JsonParser reader = Json.createParser(new StringReader(string))) {
		return fromJSON(reader);
	}
}
 
Example 15
Source Project: sample.daytrader7   File: PingJSONP.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * this is the main method of the servlet that will service all get
 * requests.
 *
 * @param request
 *            HttpServletRequest
 * @param responce
 *            HttpServletResponce
 **/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        res.setContentType("text/html");

        ServletOutputStream out = res.getOutputStream();
        
        hitCount++;
        
        // JSON generate
        StringWriter sw = new StringWriter();
        JsonGenerator generator = Json.createGenerator(sw);
         
        generator.writeStartObject();
        generator.write("initTime",initTime);
        generator.write("hitCount", hitCount);
        generator.writeEnd();
        generator.flush();
        
        String generatedJSON =  sw.toString();
        StringBuffer parsedJSON = new StringBuffer(); 
        
        // JSON parse
        JsonParser parser = Json.createParser(new StringReader(generatedJSON));
        while (parser.hasNext()) {
           JsonParser.Event event = parser.next();
           switch(event) {
              case START_ARRAY:
              case END_ARRAY:
              case START_OBJECT:
              case END_OBJECT:
              case VALUE_FALSE:
              case VALUE_NULL:
              case VALUE_TRUE:
                 break;
              case KEY_NAME:
                  parsedJSON.append(parser.getString() + ":");
                 break;
              case VALUE_STRING:
              case VALUE_NUMBER:
                  parsedJSON.append(parser.getString() + " ");
                 break;
           }
        }
        
        out.println("<html><head><title>Ping JSONP</title></head>"
                + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping JSONP</FONT><BR>Generated JSON: " + generatedJSON + "<br>Parsed JSON: " + parsedJSON + "</body></html>");
    } catch (Exception e) {
        Log.error(e, "PingJSONP.doGet(...): general exception caught");
        res.sendError(500, e.toString());

    }
}
 
Example 16
Source Project: webex-java-sdk   File: Client.java    License: MIT License 4 votes vote down vote up
private static <T> T readJson(Class<T> clazz, InputStream inputStream) {
    JsonParser parser = Json.createParser(inputStream);
    parser.next();
    return readObject(clazz, parser);
}