public Result runBoon() { String result = null; String error = null; long time; Iterator<Object> query = null; long now = System.currentTimeMillis(); try { if (!optionAsValues) { throw new UnsupportedOperationException("Not supported!"); } io.gatling.jsonpath.JsonPath jsonPath = JsonPath$.MODULE$.compile(path).right().get(); JsonParser jsonParser = new JsonParserCharArray(); Object jsonModel = jsonParser.parse(json); query = jsonPath.query(jsonModel); } catch (Exception e) { error = getError(e); } finally { time = System.currentTimeMillis() - now; if (query != null) { List<Object> res = new ArrayList<Object>(); while (query.hasNext()) { res.add(query.next()); } ObjectMapper mapper = new ObjectMapperImpl(); result = mapper.toJson(res); } return new Result("boon", time, result, error); } }
@Override public <T> T fromJson(Object json, Class<T> type) throws Exception { if (json instanceof String) { return this.objectMapper.readValue((String) json, type); } else if (json instanceof byte[]) { return this.objectMapper.readValue((byte[]) json, type); } else if (json instanceof char[]) { return this.objectMapper.readValue((char[]) json, type); } else if (json instanceof File) { return this.objectMapper.readValue((File) json, type); } else if (json instanceof InputStream) { return this.objectMapper.readValue((InputStream) json, type); } else if (json instanceof Reader) { return this.objectMapper.readValue((Reader) json, type); } else { throw new IllegalArgumentException("'json' argument must be an instance of: " + supportedJsonTypes + " , but gotten: " + json.getClass()); } }
public static Object fromJson(String str) { return json.fromJson(str); }
@Override @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T fromJson(Object json, Map<String, Object> javaTypes) throws Exception { JsonParserAndMapper parser = this.objectMapper.parser(); return (T) this.objectMapper.readValue((String) json, (Class<Collection>) classType, contentClassType); return (T) this.objectMapper.readValue((byte[]) json, (Class<Collection>) classType, contentClassType); return (T) this.objectMapper.readValue((char[]) json, (Class<Collection>) classType, contentClassType); return (T) this.objectMapper.readValue((File) json, (Class<Collection>) classType, contentClassType); return (T) this.objectMapper.readValue((InputStream) json, (Class<Collection>) classType, contentClassType); return (T) this.objectMapper.readValue((Reader) json, (Class<Collection>) classType, contentClassType);
@Test public void test_caseInsensitiveProperty_lowercase() { String json = "{\"typename\":\"Processes\",\"fields\":[{\"name\":\"process\",\"type\":\"ConversionRateProcess[]\",\"properties\":[\"REQUIRED\"]}]} "; ApiDynamicType map = objectMapper.fromJson(json, ApiDynamicType.class); puts(json); puts(objectMapper.toJson(map)); assertThat(objectMapper.fromJson(objectMapper.toJson(map)), is(objectMapper.fromJson("{\"typeName\":\"Processes\",\"fields\":[{\"name\":\"process\",\"type\":\"ConversionRateProcess[]\",\"properties\":[\"REQUIRED\"]}]}"))); }
puts( mapper.writeValueAsString( user ) ); mapper.writeValue( file, user ); User userFromFile = mapper.readValue( file, User.class ); InputStream inputStream = Files.newInputStream( path ); User userFromInput = mapper.readValue( inputStream, User.class ); puts( "userFromInput", userFromInput ); User userFromReader = mapper.readValue( reader, User.class );
private static void part12Gson() { ObjectMapper gson = JsonFactory.createUseAnnotations( true ); puts ( gson.toJson ( 1 ) ); puts ( gson.toJson ( "abcd" ) ); puts ( gson.toJson ( new Long ( 10 ) ) ); int[] values = { 1 }; puts ( gson.toJson ( values ) ); int ione = gson.fromJson("1", int.class); Integer oneI = gson.fromJson("1", Integer.class); Boolean wrapper = gson.fromJson("false", Boolean.class); String str = gson.fromJson("\"abc\"", String.class); String anotherStr = (String)gson.fromJson("[\"abc\"]", List.class).get ( 0 ); BagOfPrimitives obj = new BagOfPrimitives(); String json = gson.toJson(obj); puts (json); int[] ints = {1, 2, 3, 4, 5}; String[] strings = {"abc", "def", "ghi"}; puts ( gson.toJson ( ints ) ); // ==> prints [1,2,3,4,5] puts ( gson.toJson ( strings ) ); // ==> prints ["abc", "def", "ghi"] Collection<Integer> ints2 = Lists.list(1,2,3,4,5); puts ( gson.toJson(ints) ) ;// ==> json is [1,2,3,4,5] puts ( gson.parser ().parseList ( Integer.class, "[1,2,3,4,5]" )); //Serializing and Deserializing Generic Types TODO missing from GSON manual //Left off here https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Generic-Types }
public static void main(String[] args) throws IOException { Builder builder = new Builder(); MetadataImpl metadataImpl = builder.getMetadata(); JsonSerializerFactory jsonSerializerFactory=new JsonSerializerFactory().usePropertyOnly(); ObjectMapper mapper = JsonFactory.create(null, jsonSerializerFactory); String json = mapper.writeValueAsString(metadataImpl); System.out.println("=============" + json); File file = new File("metadata.json"); FileWriter writer = new FileWriter(file); mapper.toJson(metadataImpl, writer); writer.close(); Path path = Paths.get(file.toString()); InputStream inputStream = Files.newInputStream(path); MetadataImpl object = JsonFactory.create().readValue(inputStream, MetadataImpl.class); inputStream.close(); System.out.println("after deserialization" + mapper.writeValueAsString(object)); }
@Test public void serializingClassFieldCausesSegFault() { SomeClass someClassInstance = new SomeClass(Bug287.class); ObjectMapper mapper = JsonFactory.create(); final String json = mapper.toJson(someClassInstance); puts(json); SomeClass someClassInstance2 = mapper.readValue("{\"clazz\":\"org.boon.bugs.Bug287\"} ", SomeClass.class); ok = someClassInstance2.clazz.getName().equals("org.boon.bugs.Bug287"); }
@Test public void test198() { Data original = new Data(Integer.MAX_VALUE, Long.MAX_VALUE); System.out.println("original: \n" + original + "\n"); ObjectMapper boon = JsonFactory.create(); String serialized = boon.writeValueAsString(original); System.out.println("serialized: \n" + serialized + "\n"); Data deserialized = boon.readValue(serialized, Data.class); System.out.println("deserialized: \n" + deserialized + "\n"); String reserialized = boon.writeValueAsString(deserialized); System.out.println("reserialized: \n" + reserialized + "\n"); }
public static void main(String... args) throws Exception{ Player kevin = new Player("Kevin", "Cricket", 32, 221, new int[]{33, 66, 78, 21, 9, 200}); final ObjectMapper mapper = JsonFactory.create(); final File file = File.createTempFile("json", "exmaple.json"); mapper.writeValue(file, kevin); Player somePlayer = mapper.readValue(file, Player.class); puts("They are equal", somePlayer.equals(kevin)); }
public static <T> List<T> fromJsonArray(String str, Class<T> clazz) { return json.parser().parseList(clazz, str); }
@Override public String toJson(Object value) throws Exception { return this.objectMapper.writeValueAsString(value); }
@Override public int _writeItems(MeasurementPOJO items, Writer out) throws Exception { mapper.writeValue(out, items); return items.size(); }
@Test public void test_arrayProperty_fromSingleValue() { String json = "{\"typeName\":\"Processes\",\"fields\":{\"name\":\"process\",\"type\":\"ConversionRateProcess[]\",\"properties\":[\"REQUIRED\"]}} "; ApiDynamicType map = objectMapper.fromJson(json, ApiDynamicType.class); puts(json); puts(objectMapper.toJson(map)); assertThat(objectMapper.fromJson(objectMapper.toJson(map)), is(objectMapper.fromJson("{\"typeName\":\"Processes\",\"fields\":[{\"name\":\"process\",\"type\":\"ConversionRateProcess[]\",\"properties\":[\"REQUIRED\"]}]}"))); }
public static void part1ReadAndWriteMyBeanToAFile() throws Exception { MyBean myBean = new MyBean(); File dst = File.createTempFile( "emp", ".json" ); ObjectMapper mapper = JsonFactory.create(); puts( "json string", mapper.writeValueAsString( myBean ) ); String str = mapper.writeValueAsString ( myBean ); boolean ok = str.contains ( "{\"name\":\"Rick\"" ) || die( str ); mapper.writeValue( dst, myBean ); // where 'dst' can be File, OutputStream or Writer File src = dst; MyBean value = mapper.readValue( src, MyBean.class ); // 'src' can be File, InputStream, Reader, String ok |= value.name.contains ( "Rick" ); puts( "mybean", value ); Object root = mapper.readValue( src, Object.class ); Map<String, Object> rootAsMap = mapper.readValue( src, Map.class ); puts( "root", root ); puts( "rootAsMap", rootAsMap ); MyBean myBean1 = new MyBean(); myBean1.name = "Diana"; MyBean myBean2 = new MyBean(); myBean2.name = "Rick"; dst = File.createTempFile( "empList", ".json" ); final List<MyBean> list = Lists.list( myBean1, myBean2 ); str = mapper.writeValueAsString ( list ); puts ( "json string", mapper.writeValueAsString ( list ) ); ok |= str.contains ( "[{\"name\":\"Diana\"},{\"name\":\"Rick\"}]" ) || die (str); mapper.writeValue( dst, list ); src = dst; List<MyBean> beans = mapper.readValue( src, List.class, MyBean.class ); puts( "mybeans", beans ); }
@Test public void testWithMapUsingFactory() { JsonParserFactory jsonParserFactory = new JsonParserFactory() .useFieldsFirst() .lax() //allow loose parsing of JSON like JSON Smart .setCharset( StandardCharsets.UTF_8 ) //Set the standard charset, defaults to UTF_8 .setLazyChop( true ) //similar to chop but only does it after map.get ; JsonSerializerFactory jsonSerializerFactory = new JsonSerializerFactory() .useFieldsFirst() //one of these //.addPropertySerializer( ) customize property output //.addTypeSerializer( ) customize type output .useJsonFormatForDates() //use json dates //.addFilter( ) add a property filter to exclude properties .includeEmpty().includeNulls().includeDefaultValues() //override defaults .handleComplexBackReference() //uses identity map to track complex back reference and avoid them .setHandleSimpleBackReference( true ) //looks for simple back reference for parent .setCacheInstances( true ) //turns on caching for immutable objects ; final ObjectMapper objectMapper = JsonFactory.create(jsonParserFactory, jsonSerializerFactory); MyClass myClass = new MyClass(); final String json = objectMapper.toJson(myClass); puts(json); final MyClass myClass1 = objectMapper.readValue(json, MyClass.class); assertEquals("foo", myClass1.string); assertEquals(1, myClass1.integer); assertNull(myClass1.map); }
public static void part3_1() throws Exception { ObjectMapper mapper = JsonFactory.create(); puts( mapper.writeValueAsString( user ) ); User user2 = mapper.readValue( mapper.writeValueAsString( user ), User.class ); puts( user2 ); boolean ok = user.equals ( user2 ) || die (user.toString ()); }
@Override @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T fromJson(Object json, Map<String, Object> javaTypes) throws Exception { JsonParserAndMapper parser = this.objectMapper.parser(); return (T) this.objectMapper.readValue((String) json, (Class<Collection>) classType, contentClassType); return (T) this.objectMapper.readValue((byte[]) json, (Class<Collection>) classType, contentClassType); return (T) this.objectMapper.readValue((char[]) json, (Class<Collection>) classType, contentClassType); return (T) this.objectMapper.readValue((File) json, (Class<Collection>) classType, contentClassType); return (T) this.objectMapper.readValue((InputStream) json, (Class<Collection>) classType, contentClassType); return (T) this.objectMapper.readValue((Reader) json, (Class<Collection>) classType, contentClassType);
@Test public void test3() { final ObjectMapper mapper = JsonFactory .createUseProperties(true); ByteArrayOutputStream stream = new ByteArrayOutputStream(); MediaContent mediaContent = MediaContent.mediaContent(); //String uri, String title, int width, int height, Size size mapper.writeValue(stream, mediaContent); MediaContent mediaContent2 = mapper.readValue(stream.toByteArray(), MediaContent.class); boolean ok = mediaContent.equals(mediaContent2) || die(); }