/** * Turn this into jet json * @return json */ @Override public JsonObject toJSON() { final JsonObjectBuilder b = Json.createObjectBuilder(); for ( Map.Entry<String,JsonValue> entry : super.toJSON().entrySet()) { if ( entry.getKey().equals( "return_refund_feedback" )) b.add( "refund_feedback", entry.getValue()); else b.add( entry.getKey(), entry.getValue()); } b.add( "refund_reason", refundReason.getText()); return b.build(); }
public void mergeProperties(final String properties) { if (StringUtils.isEmpty(properties)) { return; } if (StringUtils.isEmpty(getProperties())) { setProperties(properties); return; } final JsonReaderFactory fact = Json.createReaderFactory(null); final JsonReader r1 = fact.createReader(new StringReader(getProperties())); final JsonObjectBuilder jbf = Json.createObjectBuilder(r1.readObject()); final JsonReader r2 = fact.createReader(new StringReader(getProperties())); final JsonObject obj2 = r2.readObject(); for (Entry<String, JsonValue> jv : obj2.entrySet()) { jbf.add(jv.getKey(), jv.getValue()); } setProperties(jbf.build().toString()); }
@Override public User signUp() { final JsonArray registered = this.server.storage().build() .getJsonArray("users"); final JsonArrayBuilder users = Json.createArrayBuilder(); for(final JsonValue user: registered) { users.add(user); } users.add( Json.createObjectBuilder() .add( this.json.getString("username"), this.json ) ); this.server.storage().add("users", users.build()); return new MkUser(this.server, this.json.getString("username")); }
private void convert(JsonValue json) { if (json == null) { builder.append("null"); return; } if (json instanceof JsonObject) { convert(((JsonObject) json)); return; } if (json instanceof JsonArray) { convert(((JsonArray) json)); return; } builder.append(json.toString()); }
private void convert(JsonObject json) { int i =0; builder.append("Json.createObjectBuilder()\n"); for (Map.Entry<String, JsonValue> entry : json.entrySet()) { builder.append(spaces() + indent() + ".add("); String key = entry.getKey(); JsonValue value = entry.getValue(); builder.append('"'); builder.append(key); builder.append('"'); builder.append(", "); builder.append(new JsonConversion(indent + INDENT_INCREMENT).execute(value)); builder.append(")"); if(i++ != json.size() -1 ){ builder.append("\n"); } } }
public static void addValue(JsonObjectBuilder obj, String key, Object value) { if (value instanceof Integer) { obj.add(key, (Integer)value); } else if (value instanceof String) { obj.add(key, (String)value); } else if (value instanceof Float) { obj.add(key, (Float)value); } else if (value instanceof Double) { obj.add(key, (Double)value); } else if (value instanceof Boolean) { obj.add(key, (Boolean)value); } else if (value instanceof JsonValue) { JsonValue val = (JsonValue)value; obj.add(key, val); } // Add more cases here }
/** * This method adds teams of the specified page to the teams array. * * @param arrBuilder specifies the array builder to add the teams into. * @param year specifies the optional year, null for all years. * @param pageNum specifies the page number. * @param verbosity specifies optional verbosity, null for full verbosity. * @param statusOut specifies standard output stream for command status, can be null for quiet mode. * @return true if successful, false if failed. */ private boolean addTeams( JsonArrayBuilder arrBuilder, String year, int pageNum, String verbosity, PrintStream statusOut) { String request = "teams/"; if (year != null) request += year + "/"; request += pageNum; if (verbosity != null) request += "/" + verbosity; JsonStructure data = get(request, statusOut, header); boolean success; if (data != null && data.getValueType() == JsonValue.ValueType.ARRAY && !((JsonArray)data).isEmpty()) { for (JsonValue team: (JsonArray)data) { arrBuilder.add(team); } success = true; } else { success = false; } return success; }
JwksResponse(JsonObject jsonObject) { JsonValue keys = jsonObject.get("keys"); if (keys.getValueType() != JsonValue.ValueType.ARRAY) { _keys = Collections.emptyList(); } else { _keys = Stream.of((JsonArray)keys) .filter(it -> it.getValueType() == JsonValue.ValueType.OBJECT) .map(it -> (JsonObject) it) .map(JsonWebKey::new) .collect(Collectors.toList()); } }
/** * Converts a {@link JsonValue} to its corresponding Java object. Values of type {@link * JsonObject} or {@link JsonArray} are converted as specified by {@link #toJavaMap} and {@link * #toJavaList}, respectively. */ @Nullable public static Object toJavaObject(JsonValue value) { switch (value.getValueType()) { case ARRAY: return toJavaList((JsonArray) value); case FALSE: return Boolean.FALSE; case NULL: return null; case NUMBER: JsonNumber number = (JsonNumber) value; return number.isIntegral() ? number.intValue() : number.doubleValue(); case OBJECT: return toJavaMap((JsonObject) value); case STRING: return ((JsonString) value).getString(); case TRUE: return Boolean.TRUE; default: throw new VerifyException("Json value with unknown type: " + value); } }
@Override public Response handle() throws Exception { String ref = getRequest().getVariableValue(":reference"); RemoteWebElement element = getWebDriver().createElement(ref); JsonArray array = getRequest().getPayload().getJsonArray("value"); String value = ""; for (JsonValue jsonValue : array) { value += JavaxJson.toJavaObject(jsonValue); } element.setValueAtoms(value); Response res = new Response(); res.setSessionId(getSession().getSessionId()); res.setStatus(0); res.setValue(new JSONObject()); return res; }
public void findCustomerByAddress() { searchResult = null; String text = "/" + this.addressSearchText; JsonObject json = Json.createObjectBuilder().build(); JsonValue object = json.getJsonObject(fetchJson()); if (addressSearchText != null) { JsonPointer pointer = Json.createPointer(text); JsonValue result = pointer.getValue(object.asJsonArray()); // Replace a value JsonArray array = (JsonArray) pointer.replace(object.asJsonArray(), Json.createValue("1000 JsonP Drive")); searchResult = array.toString(); //searchResult = result.toString(); } }
public static Object unbox(JsonValue value, Function<JsonStructure, Object> convert) throws JsonException { switch (value.getValueType()) { case ARRAY: case OBJECT: return convert.apply((JsonStructure) value); case FALSE: return Boolean.FALSE; case TRUE: return Boolean.TRUE; case NULL: return null; case NUMBER: JsonNumber number = (JsonNumber) value; return number.isIntegral() ? number.longValue() : number.doubleValue(); case STRING: return ((JsonString) value).getString(); default: throw new JsonException("Unknow value type"); } }
public JsonObject save(JsonObject input, String href, String date) { String id = href.substring(href.lastIndexOf('/') +1); JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add("id", id); builder.add("date", date); JsonObject jsonLink = Json.createObjectBuilder() .add("rel", Json.createArrayBuilder().add("self").build()) .add("href", href) .build(); builder.add("links", jsonLink); for (Map.Entry<String, JsonValue> entry : input.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } JsonObject storedObject = builder.build(); exampleStore.put(id, storedObject); return storedObject; }
private Object plainifyJsonValue(final JsonValue jval) { switch (jval.getValueType()) { case ARRAY: return plainifyJsonArray((JsonArray) jval); case FALSE: return Boolean.FALSE; case TRUE: return Boolean.TRUE; case NULL: return null; case NUMBER: return ((JsonNumber) jval).bigDecimalValue(); case OBJECT: return plainifyJsonObject((JsonObject) jval); case STRING: return ((JsonString) jval).getString(); default: throw new RuntimeException("unexpected json type"); } }
@Override public Object parse (String jsonString) throws InvalidJsonException { try { Reader r = new StringReader (jsonString); TextJsonParser p = new TextJsonParser (r); p.next (); // read the very first token to get initiated. JsonValue v = p.getValue (); p.close (); return v; } catch (JsonException ex) { throw new InvalidJsonException (ex); } }
@Override public JsonGenerator write (String name, JsonValue value) { // assert Debug.debug ("WRITE: KEY_NAME: " + name); // assert Debug.debug ("WRITE: JsonValue"); if (m_state != GeneratorState.IN_OBJECT) throw new JsonGenerationException (ErrorMessage.notInObjectContext); try { writeName (name); writeValue (value); return this; } catch (IOException ex) { throw new JsonGenerationException (ex.getMessage (), ex); } }
@Test public void allMatch() { String json = "{ \"noon\": {}, \"racecar\": {}, \"kayak\": {} }"; JsonValidator validator = new BasicJsonValidator(createSchema()); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertThat(result.hasProblems(), is(false)); JsonValue v = result.getValue(); assertThat(v, is(instanceOf(JsonObject.class))); JsonObject o = (JsonObject)v; assertThat(o.getJsonObject("noon"), is(notNullValue())); assertThat(o.getJsonObject("racecar"), is(notNullValue())); assertThat(o.getJsonObject("kayak"), is(notNullValue())); }
private void testFile (String f) throws IOException { File file = new File (f.replace ('/', File.separatorChar)); StringWriter out1 = new StringWriter (); TextJsonParser p1 = getJsonParser (file); p1.next (); JsonValue v = p1.getValue (); TextJsonGenerator g1 = new PrettyTextJsonGenerator (out1); g1.write (v); p1.close (); g1.close (); StringWriter out2 = new StringWriter (); TextJsonParser p2 = getJsonParser (file); JsonGenerator g2 = new PrettyTextJsonGenerator (out2); Utils.convert (p2, g2); p2.close (); g2.close (); // because JsonObject ordering is based on hash, we cannot directly // compare the output. Instead, we compare the length. Assert.assertEquals (out1.toString ().length (), out2.toString ().length ()); }
public static LocalTime getLocalTime( JsonObject o, String n ) { JsonValue v = o.get( n ); if( v == null ) { return null; } switch( v.getValueType() ) { case STRING: return TimeUtils.getLocalTime( ((JsonString) v).getString() ); case NUMBER: return TimeUtils.getLocalTime( ((JsonNumber) v).longValue() ); default: return null; } }
@Test public void trueToFalse() { String json = "[true]"; Schema schema = schema(array(bool().enumeration(false))); JsonValidator validator = new BasicJsonValidator(schema); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertEquals(1, result.getProblems().size()); assertTrue(result.getProblems().get(0) instanceof NoSuchEnumeratorProblem); NoSuchEnumeratorProblem p = (NoSuchEnumeratorProblem)result.getProblems().get(0); assertEquals(JsonValue.TRUE, p.getCauseValue()); Set<Object> expected = p.getEnumerators(); assertEquals(1, expected.size()); assertTrue(expected.contains(Boolean.FALSE)); assertNotNull(p.getDescription()); }
private Map<String, String> jsonToMap(JsonObject jsonOutput) { Map<String, String> resultMap = new HashMap<>(); for(String key:jsonOutput.keySet()) { JsonValue value = jsonOutput.get(key); if(value.getValueType() == ValueType.STRING) { resultMap.put(key, jsonOutput.getString(key)); } else if (!value.getValueType().equals(ValueType.OBJECT)&&!value.getValueType().equals(ValueType.ARRAY)) { resultMap.put(key, jsonOutput.getString(key).toString()); } } return resultMap; }
private SchemaMetadataInfo parseMetadataInfo(JsonObject root) { JsonObject meta = root.getJsonObject("schemaMetadataInfo"); if (meta == null) { return null; } String schemaName = meta.getString("name"); String schemaAdapterNotes = readAdapterNotes(meta); Map<String, String> properties = new HashMap<String, String>(); if (meta.getJsonObject("properties") != null) { for (Map.Entry<String, JsonValue> entry : meta.getJsonObject("properties").entrySet()) { String key = entry.getKey(); properties.put(key.toUpperCase(), meta.getJsonObject("properties").getString(key)); } } return new SchemaMetadataInfo(schemaName, schemaAdapterNotes, properties); }
/** * * @param data */ Attribute(JsonObject data) throws ResponseDataException { super(data); if (data.get("Options") == null) { throw new ResponseDataException("Cannot create attribute"); } if (data.get("Options") instanceof JsonObject) { JsonValue option = data.getJsonObject("Options").get("Option"); if (option == null) { throw new ResponseDataException("Cannot create attribute"); } if (option instanceof JsonArray) { for (JsonValue opt : (JsonArray) option) { if (opt instanceof JsonObject) { options.add(new AttributeOption((JsonObject) opt)); } } } else if (option instanceof JsonObject) { options.add(new AttributeOption((JsonObject) option)); } } }
@Test public void someNotMatch() { String json = "{ \"radar\": {}, \"word\": {}, \"level\": {} }"; JsonValidator validator = new BasicJsonValidator(createSchema()); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); List<Problem> problems = result.getProblems(); assertThat(problems.size(), equalTo(1)); assertThat(problems.get(0), is(instanceOf(UnknownPropertyProblem.class))); UnknownPropertyProblem p0 = (UnknownPropertyProblem)problems.get(0); assertThat(p0.getPropertyName(), equalTo("word")); assertThat(p0.getDescription(), is(notNullValue())); JsonValue v = result.getValue(); assertThat(v, is(instanceOf(JsonObject.class))); JsonObject o = (JsonObject)v; assertThat(o.getJsonObject("radar"), is(notNullValue())); assertThat(o.getJsonObject("word"), is(notNullValue())); assertThat(o.getJsonObject("level"), is(notNullValue())); }
/** * @param response api response to GetOrderItems or GetMultipleOrderItems */ OrderItemCollection(SuccessResponse response) throws SdkException { JsonObject body = response.getBody(); JsonObject orders = body.getJsonObject("Orders"); if (orders == null) { // single order via GetOrderItems extractItems(body); } else { JsonValue order = orders.get("Order"); if (order instanceof JsonArray) { // multiple orders via GetMultipleOrderItems for (JsonValue o : ((JsonArray) order)) { if (o instanceof JsonObject) { extractItems((JsonObject) o); } } } else if (order instanceof JsonObject) { // single orders via GetMultipleOrderItems extractItems((JsonObject) order); } } }
/** * Parse JSON of body or order object and gather all order items * * @param container body or order json object */ private void extractItems(JsonObject container) throws SdkException { if (container.getJsonObject("OrderItems") == null || container.getJsonObject("OrderItems").get("OrderItem") == null) { throw new ResponseDataException("Cannot create OrderItemCollection"); } JsonValue orderItem = container.getJsonObject("OrderItems").get("OrderItem"); if (orderItem instanceof JsonObject) { items.add(new OrderItem((JsonObject) orderItem)); } else if (orderItem instanceof JsonArray) { for (JsonValue item : (JsonArray) orderItem) { if (item instanceof JsonObject) { items.add(new OrderItem((JsonObject) item)); } } } }
/** * @param response response from the API */ OrderCollection(SuccessResponse response) throws ResponseDataException { if (response.getBody().get("Orders") == null) { throw new ResponseDataException("Cannot create OrderCollection"); } if (response.getBody().get("Orders") instanceof JsonObject) { if (response.getBody().getJsonObject("Orders").get("Order") == null) { throw new ResponseDataException("Cannot create OrderCollection"); } JsonValue orders = response.getBody().getJsonObject("Orders").get("Order"); if (orders instanceof JsonArray) { for (JsonValue order : (JsonArray) orders) { if (order instanceof JsonObject) { this.orders.add(new Order((JsonObject) order)); } } } else if (orders instanceof JsonObject) { this.orders.add(new Order((JsonObject) orders)); } } }
private static String readAdapterNotes(JsonObject root) { if (root.containsKey("adapterNotes")) { JsonValue notes = root.get("adapterNotes"); if (notes.getValueType() == ValueType.STRING) { // Return unquoted string return ((JsonString)notes).getString(); } else { return notes.toString(); } } return ""; }
public void load(final Trie s) { try (InputStream in = Files.newInputStream(filePath); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { String line; final Set<Fact> facts = new TreeSet<Fact>(); while ((line = reader.readLine()) != null) { if (line.compareTo(" ") > 0) { try (JsonReader json = Json.createReader(new StringReader(line))) { final JsonObject o = json.readObject(); final Fact f = new Fact(o, context); if (o.get("deleted") == JsonValue.TRUE) { facts.remove(f); } else { facts.add(f); } } } } facts.parallelStream().forEach((f) -> s.insertAll(f, context)); context.commit(); } catch (IOException e) { throw new RuntimeException(e); } }
@Test public void testJsonPointer() { JsonReader reader = Json.createReader(JsonpTest.class.getResourceAsStream("/persons.json")); JsonArray arrays = reader.readArray(); JsonPointer p = Json.createPointer("/0/name"); JsonValue name = p.getValue(arrays); System.out.println("json value ::" + name); // assertEquals("Duke", name.toString()); JsonReader objReader = Json.createReader(JsonpTest.class.getResourceAsStream("/person.json")); JsonPointer p2 = Json.createPointer("/name"); JsonValue name2 = p2.getValue(objReader.readObject()); System.out.println("json value ::" + name2); // assertEquals("Duke", name2.toString()); }
/** * Loads JSON content from specified resource. * @param name name of resource to load. * @param validator validator for this JSON content. * @return JSON value loaded. */ public static JsonValue load(String name, JsonValidator validator) { System.out.println("Validating JSON file: \"" + name + "\""); InputStream stream = JsonLoader.class.getResourceAsStream(name); try (Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { long startTime = System.currentTimeMillis(); ValidationResult result = validator.validate(reader); long endTime = System.currentTimeMillis(); long elapsed = endTime - startTime; printProblems(result); System.out.println("Time elapsed: " + elapsed + " ms"); printValue(result); return result.getValue(); } catch (IOException e) { System.err.println(e.toString()); return null; } }
@Test public void objectWithUnknownProperty() { JsonValidator validator = new BasicJsonValidator(createSchema()); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); List<Problem> problems = result.getProblems(); assertThat(problems.size(), equalTo(1)); assertThat(problems.get(0), instanceOf(UnknownPropertyProblem.class)); UnknownPropertyProblem p = (UnknownPropertyProblem)problems.get(0); assertThat(p.getPointer().toString(), equalTo("")); assertThat(p.getCauseValue().getValueType(), is(JsonValue.ValueType.OBJECT)); assertThat(p.getPropertyName(), equalTo("h")); assertThat(p.getDescription(), is(notNullValue())); }
private final List<Speaker> parseSpeaker(URL speakerResource) { try { final JsonReaderFactory factory = Json.createReaderFactory(null); final JsonReader reader = factory.createReader(speakerResource.openStream()); final JsonArray items = reader.readArray(); // parse session objects final List<Speaker> speaker = new LinkedList<>(); for (final JsonValue item : items) { final Speaker s = new Speaker((JsonObject) item); s.setId(String.valueOf(this.speakerId.incrementAndGet())); speaker.add(s); } return speaker; } catch (Exception e) { throw new RuntimeException("Failed to parse speaker.json"); } }
@Test public void testJsonValue () throws IOException { File file1 = new File ("../tests/data/complex1.json".replace ('/', File.separatorChar)); // first convert from Json to Bson using stream API File bsonFile = testFolder.newFile (); CookJsonParser p = TextJsonConfigHandler.getJsonParser (new FileInputStream (file1)); JsonGenerator g = new BsonGenerator (new FileOutputStream (bsonFile)); Utils.convert (p, g); p.close (); g.close (); // convert from Json to Bson using tree api File bsonFile2 = testFolder.newFile (); p = TextJsonConfigHandler.getJsonParser (new FileInputStream (file1)); p.next (); JsonValue value = p.getValue (); p.close (); g = new BsonGenerator (new FileOutputStream (bsonFile2)); g.write (value); g.close (); // due to object ordering, we can only compare the length. Assert.assertEquals (bsonFile.length (), bsonFile2.length ()); }
private static String getJsonValue(JsonValue value) { String s = null; if (value != null) { s = getJsonValueAsString(value); if (s == null) { s = getJsonValueAsNumberString(value); } if (s == null) { Boolean b = getJsonValueAsBoolean(value); if (b != null) { s = b ? "true" : "false"; } } } return s; }
@Override public JsonValue getValue () { switch (m_event) { case START_ARRAY: case START_OBJECT: return Utils.getStructure (this); case END_ARRAY: case END_OBJECT: case KEY_NAME: throw stateError ("getValue()"); case VALUE_TRUE: return JsonValue.TRUE; case VALUE_FALSE: return JsonValue.FALSE; case VALUE_NULL: return JsonValue.NULL; case VALUE_NUMBER: return new CookJsonBigDecimal (getBigDecimal ()); case VALUE_STRING: return new CookJsonString (getString ()); } throw stateError ("getValue()"); }
/** * Looks up a {@link JsonValue} which is referenced by a given JSON pointer. * @param pointer the JSON pointer which refers to a {@link JsonValue}. * @return the {@link JsonValue} if found, {@code null} otherwise. * @exception IllegalArgumentException if specified pointer is {@code null}. */ public JsonValue getValueByPointer(JsonPointer pointer) { if (pointer == null) { throw new IllegalArgumentException(); } JsonValue current = getRootValue(); for (Object token: pointer) { if (current == null) { break; } JsonValue.ValueType type = current.getValueType(); if (type == JsonValue.ValueType.ARRAY) { if ((token instanceof Integer)) { int index = ((Integer)token).intValue(); current = ((JsonArray)current).get(index); } else { current = null; } } else if (type == JsonValue.ValueType.OBJECT) { current = ((JsonObject)current).get(token); } else { break; } } return current; }
@Test public void allMatch() { String json = "{" + "\"name\": \"Solar System\"," + "\"center\": \"Sun\"," + "\"1st\": \"Mercury\"," + "\"4th\": \"Mars\"," + "\"comets\": [ \"Hale-Bopp\" ]" + "}"; JsonValidator validator = new BasicJsonValidator(createSchema()); ValidationResult result = validator.validate(new StringReader(json)); assertResultValid(result, json); assertThat(result.hasProblems(), is(false)); JsonValue v = result.getValue(); assertThat(v, is(instanceOf(JsonObject.class))); JsonObject o = (JsonObject)v; assertThat(o.getString("name"), equalTo("Solar System")); assertThat(o.getString("center"), equalTo("Sun")); assertThat(o.getString("1st"), equalTo("Mercury")); assertThat(o.getString("4th"), equalTo("Mars")); assertThat(o.getJsonArray("comets").getString(0), equalTo("Hale-Bopp")); }
void testBsonFile (String f) throws IOException { File file = new File (f.replace ('/', File.separatorChar)); StringWriter out1 = new StringWriter (); BsonParser p1 = new BsonParser (new FileInputStream (file)); p1.next (); JsonValue v = p1.getValue (); TextJsonGenerator g1 = new PrettyTextJsonGenerator (out1); g1.write (v); p1.close (); g1.close (); ByteArrayOutputStream bos = new ByteArrayOutputStream (); BsonParser p2 = new BsonParser (new FileInputStream (file)); JsonGenerator g2 = new PrettyTextJsonGenerator (bos); Utils.convert (p2, g2); p2.close (); g2.close (); // because JsonObject ordering is based on hash, we cannot directly // compare the output. Instead, we compare the length. Assert.assertEquals (new String (bos.toByteArray (), BOM.utf8).length (), out1.toString ().length ()); }
public static Time getTime( JsonValue v ) { if( v == null ) { return null; } switch( v.getValueType() ) { case NUMBER: return new Time( ((JsonNumber) v).longValue() ); case STRING: return Time.valueOf( ((JsonString) v).getString() ); case TRUE: case FALSE: case NULL: return null; default: return Time.valueOf( v.toString() ); } }