com.jayway.jsonpath.Configuration Java Examples

The following examples show how to use com.jayway.jsonpath.Configuration. 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
Source File: EnrichIntegrationJsonPathTestCase.java    From micro-integrator with Apache License 2.0 7 votes vote down vote up
private void setJsonPathConfiguration() {
    Configuration.setDefaults(new Configuration.Defaults() {

        private final JsonProvider jsonProvider = new GsonJsonProvider(new GsonBuilder().serializeNulls().create());
        private final MappingProvider mappingProvider = new GsonMappingProvider();

        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #2
Source File: LightServer.java    From light with Apache License 2.0 6 votes vote down vote up
static void configJsonPath() {
    Configuration.setDefaults(new Configuration.Defaults() {

        private final JsonProvider jsonProvider = new JacksonJsonProvider();
        private final MappingProvider mappingProvider = new JacksonMappingProvider();

        @Override
        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        @Override
        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        @Override
        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #3
Source File: PropertiesBuilder.java    From querqy with Apache License 2.0 6 votes vote down vote up
public PropertiesBuilder() {
    objectMapper = new ObjectMapper();
    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
    objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true);



    jsonPathConfiguration = Configuration.builder()
            .jsonProvider(new JacksonJsonProvider())
            .mappingProvider(new JacksonMappingProvider()).build();
    jsonPathConfiguration.addOptions(Option.ALWAYS_RETURN_LIST);

    primitiveProperties = new HashMap<>();
    jsonObjectString =  new StringBuilder();

}
 
Example #4
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * JSONObjects can be built from a Map<String, Object>. 
 * In this test all of the map entries are valid JSON types.
 */
@Test
public void jsonObjectByMap() {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("trueKey", new Boolean(true));
    map.put("falseKey", new Boolean(false));
    map.put("stringKey", "hello world!");
    map.put("escapeStringKey", "h\be\tllo w\u1234orld!");
    map.put("intKey", new Long(42));
    map.put("doubleKey", new Double(-23.45e67));
    JSONObject jsonObject = new JSONObject(map);

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
    assertTrue("expected 6 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 6);
    assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey")));
    assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey")));
    assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey")));
    assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey")));
    assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey")));
}
 
Example #5
Source File: InstructionsPropertiesTest.java    From querqy with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatches() {

    final Map<String, Object> props = new HashMap<>();
    props.put("p1", 1);
    props.put("p2", "2");
    props.put("p3", Arrays.asList("3", 33));

    final Map<String, Object> p4 = new HashMap<>();
    p4.put("p41", "41");
    p4.put("p42", 42);
    props.put("p4", p4);

    final InstructionsProperties instructionsProperties = new InstructionsProperties(props, Configuration.builder()
            .jsonProvider(new JacksonJsonProvider()).mappingProvider(new JacksonMappingProvider()).build());

    assertTrue(instructionsProperties.matches("$[?(@.p2 == '2')]"));
    assertFalse(instructionsProperties.matches("$.[?(@.p2 == 1)]"));

    assertTrue(instructionsProperties.matches("$.p3[?(@ == '3')]"));
    assertTrue(instructionsProperties.matches("$.p4[?(@.p42 == 42)]"));
    assertTrue(instructionsProperties.matches("$.p4[?(@.p42 > 5)]"));


}
 
Example #6
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * JSONObjects can be built from a Map<String, Object>. 
 * In this test the map entries are not valid JSON types.
 * The actual conversion is kind of interesting.
 */
@Test
public void jsonObjectByMapWithUnsupportedValues() {
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    // Just insert some random objects
    jsonMap.put("key1", new CDL());
    jsonMap.put("key2", new Exception());

    JSONObject jsonObject = new JSONObject(jsonMap);

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
    assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
    assertTrue("expected 0 key1 items", ((Map<?,?>)(JsonPath.read(doc, "$.key1"))).size() == 0);
    assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2")));
}
 
Example #7
Source File: JSONIO.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
public DocumentContext parseJSON( File jsonFile ) throws ManipulationException
{
    if ( jsonFile == null || !jsonFile.exists() )
    {
        throw new ManipulationException( "JSON File not found" );
    }

    this.encoding = detectEncoding( jsonFile );
    this.charset = Charset.forName( encoding.getJavaName() );
    this.jsonFile = jsonFile;
    this.eol = detectEOL( jsonFile );

    DocumentContext doc;

    try ( FileInputStream in = new FileInputStream( jsonFile ) )
    {
        Configuration conf = Configuration.builder().options( Option.ALWAYS_RETURN_LIST ).build();
        doc = JsonPath.using( conf ).parse( in, charset.name() );
    }
    catch ( IOException e )
    {
        logger.error( "Unable to parse JSON File", e );
        throw new ManipulationException( "Unable to parse JSON File", e );
    }
    return doc;
}
 
Example #8
Source File: MaskTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void runOnceBeforeClass() {
    Configuration.setDefaults(new Configuration.Defaults() {

        private final JsonProvider jsonProvider = new JacksonJsonProvider();
        private final MappingProvider mappingProvider = new JacksonMappingProvider();

        @Override
        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        @Override
        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        @Override
        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #9
Source File: TestSchemaValidator.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void init() {
    // Set GsonJsonProvider as the default Jayway JSON path default configuration
    // Which is set by synapse-core at runtime of the server
    Configuration.setDefaults(new Configuration.Defaults() {
        private final JsonProvider jsonProvider = new GsonJsonProvider(new GsonBuilder().serializeNulls().create());
        private final MappingProvider mappingProvider = new GsonMappingProvider();

        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #10
Source File: JsonPathIntegrationCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public Integration apply(Integration integration) {
    if (ObjectHelper.isEmpty(expression)) {
        return integration;
    }

    try {
        final Configuration configuration = Configuration.builder()
                .jsonProvider(new JacksonJsonProvider(JsonUtils.copyObjectMapperConfiguration()))
                .mappingProvider(new JacksonMappingProvider(JsonUtils.copyObjectMapperConfiguration()))
                .build();

        DocumentContext json = JsonPath.using(configuration).parse(JsonUtils.writer().forType(Integration.class).writeValueAsString(integration));

        if (ObjectHelper.isEmpty(key)) {
            json.set(expression, value);
        } else {
            json.put(expression, key, value);
        }

        return JsonUtils.reader().forType(Integration.class).readValue(json.jsonString());
    } catch (IOException e) {
        throw new IllegalStateException("Failed to evaluate json path expression on integration object", e);
    }
}
 
Example #11
Source File: JsonPathStartupHookProvider.java    From light-4j with Apache License 2.0 6 votes vote down vote up
static void configJsonPath() {
    Configuration.setDefaults(new Configuration.Defaults() {

        private final JsonProvider jsonProvider = new JacksonJsonProvider();
        private final MappingProvider mappingProvider = new JacksonMappingProvider();

        @Override
        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        @Override
        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        @Override
        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #12
Source File: JsonPathTest.java    From light with Apache License 2.0 6 votes vote down vote up
@Override
public Object map(Object currentValue, Configuration configuration) {
    if(currentValue instanceof Map) {
        ((Map) currentValue).remove("roles");
        ((Map) currentValue).remove("credential");
        ((Map) currentValue).remove("createDate");
        ((Map) currentValue).remove("host");
        ((Map) currentValue).remove("out_Create");
        String rid = (String)((Map) currentValue).get("@rid");
        if(userMap.get(rid) == null) {
            userMap.put(rid, currentValue);
        }
    } else if(currentValue instanceof String) {
        currentValue = userMap.get((String)currentValue);
    }
    return currentValue;
}
 
Example #13
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * Exercise the JSONObject from resource bundle functionality.
 * The test resource bundle is uncomplicated, but provides adequate test coverage.
 */
@Test
public void jsonObjectByResourceBundle() {
    JSONObject jsonObject = new
            JSONObject("org.json.junit.data.StringsResourceBundle",
                    Locale.getDefault());

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
    assertTrue("expected 2 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 2);
    assertTrue("expected 2 greetings items", ((Map<?,?>)(JsonPath.read(doc, "$.greetings"))).size() == 2);
    assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(jsonObject.query("/greetings/hello")));
    assertTrue("expected \"world\":\"World!\"", "World!".equals(jsonObject.query("/greetings/world")));
    assertTrue("expected 2 farewells items", ((Map<?,?>)(JsonPath.read(doc, "$.farewells"))).size() == 2);
    assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later")));
    assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator")));
}
 
Example #14
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * A JSONObject can be created from another JSONObject plus a list of names.
 * In this test, some of the starting JSONObject keys are not in the 
 * names list.
 */
@Test
public void jsonObjectByNames() {
    String str = 
        "{"+
            "\"trueKey\":true,"+
            "\"falseKey\":false,"+
            "\"nullKey\":null,"+
            "\"stringKey\":\"hello world!\","+
            "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+
            "\"intKey\":42,"+
            "\"doubleKey\":-23.45e67"+
        "}";
    String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"};
    JSONObject jsonObject = new JSONObject(str);

    // validate JSON
    JSONObject jsonObjectByName = new JSONObject(jsonObject, keys);
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString());
    assertTrue("expected 4 top level items", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 4);
    assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObjectByName.query("/falseKey")));
    assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey")));
    assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey")));
    assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObjectByName.query("/doubleKey")));
}
 
Example #15
Source File: JsonFunctions.java    From calcite with Apache License 2.0 6 votes vote down vote up
public static String jsonRemove(JsonValueContext input, String... pathSpecs) {
  try {
    DocumentContext ctx = JsonPath.parse(input.obj,
        Configuration
            .builder()
            .options(Option.SUPPRESS_EXCEPTIONS)
            .jsonProvider(JSON_PATH_JSON_PROVIDER)
            .mappingProvider(JSON_PATH_MAPPING_PROVIDER)
            .build());
    for (String pathSpec : pathSpecs) {
      if ((pathSpec != null) && (ctx.read(pathSpec) != null)) {
        ctx.delete(pathSpec);
      }
    }
    return ctx.jsonString();
  } catch (Exception ex) {
    throw RESOURCE.invalidInputForJsonRemove(
        input.toString(), Arrays.toString(pathSpecs)).ex();
  }
}
 
Example #16
Source File: JSONRecordFactory.java    From rmlmapper-java with MIT License 6 votes vote down vote up
/**
 * This method returns the records from a JSON document based on an iterator.
 * @param document the document from which records need to get.
 * @param iterator the used iterator.
 * @return a list of records.
 * @throws IOException
 */
@Override
List<Record> getRecordsFromDocument(Object document, String iterator) throws IOException {
    List<Record> records = new ArrayList<>();

    Configuration conf = Configuration.builder()
            .options(Option.AS_PATH_LIST).build();

    try {
        List<String> pathList = JsonPath.using(conf).parse(document).read(iterator);

        for(String p :pathList) {
            records.add(new JSONRecord(document, p));
        }
    } catch(PathNotFoundException e) {
        logger.warn(e.getMessage(), e);
    }

    return records;
}
 
Example #17
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * Populate a JSONArray from a JSONObject names() method.
 * Confirm that it contains the expected names.
 */
@Test
public void jsonObjectNamesToJsonAray() {
    String str = 
        "{"+
            "\"trueKey\":true,"+
            "\"falseKey\":false,"+
            "\"stringKey\":\"hello world!\","+
        "}";

    JSONObject jsonObject = new JSONObject(str);
    JSONArray jsonArray = jsonObject.names();

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
    assertTrue("expected 3 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 3);
    assertTrue("expected to find trueKey", ((List<?>) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1);
    assertTrue("expected to find falseKey", ((List<?>) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1);
    assertTrue("expected to find stringKey", ((List<?>) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1);
}
 
Example #18
Source File: ServiceIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenStructure_whenRequestingHighestRevenueMovieTitle_thenSucceed() {
    DocumentContext context = JsonPath.parse(jsonString);
    List<Object> revenueList = context.read("$[*]['box office']");
    Integer[] revenueArray = revenueList.toArray(new Integer[0]);
    Arrays.sort(revenueArray);

    int highestRevenue = revenueArray[revenueArray.length - 1];
    Configuration pathConfiguration = Configuration.builder()
        .options(Option.AS_PATH_LIST)
        .build();
    List<String> pathList = JsonPath.using(pathConfiguration)
        .parse(jsonString)
        .read("$[?(@['box office'] == " + highestRevenue + ")]");

    Map<String, String> dataRecord = context.read(pathList.get(0));
    String title = dataRecord.get("title");

    assertEquals("Skyfall", title);
}
 
Example #19
Source File: EnrichIntegrationJsonPathTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
private void setJsonPathConfiguration() {
    Configuration.setDefaults(new Configuration.Defaults() {

        private final JsonProvider jsonProvider = new GsonJsonProvider(new GsonBuilder().serializeNulls().create());
        private final MappingProvider mappingProvider = new GsonMappingProvider();

        public JsonProvider jsonProvider() {
            return jsonProvider;
        }

        public MappingProvider mappingProvider() {
            return mappingProvider;
        }

        public Set<Option> options() {
            return EnumSet.noneOf(Option.class);
        }
    });
}
 
Example #20
Source File: FastJsonReader.java    From hop with Apache License 2.0 6 votes vote down vote up
private Configuration deleteOptionFromConfiguration( Configuration config, Option option ) {
  Configuration currentConf = config;
  if ( currentConf != null ) {
    EnumSet<Option> currentOptions = EnumSet.noneOf( Option.class );
    currentOptions.addAll( currentConf.getOptions() );
    if ( currentOptions.remove( option ) ) {
      if ( log.isDebug() ) {
        log.logDebug( BaseMessages.getString( PKG, "JsonReader.Debug.Configuration.Option.Delete", option ) );
      }
      currentConf = Configuration.defaultConfiguration().addOptions( currentOptions.toArray( new Option[currentOptions.size()] ) );
    }
  }
  if ( log.isDebug() ) {
    log.logDebug( BaseMessages.getString( PKG, "JsonReader.Debug.Configuration.Options", currentConf.getOptions() ) );
  }
  return currentConf;
}
 
Example #21
Source File: JsonFunctions.java    From Quicksql with MIT License 6 votes vote down vote up
public static String jsonRemove(JsonValueContext input, String... pathSpecs) {
  try {
    DocumentContext ctx = JsonPath.parse(input.obj,
        Configuration
            .builder()
            .options(Option.SUPPRESS_EXCEPTIONS)
            .jsonProvider(JSON_PATH_JSON_PROVIDER)
            .mappingProvider(JSON_PATH_MAPPING_PROVIDER)
            .build());
    for (String pathSpec : pathSpecs) {
      if ((pathSpec != null) && (ctx.read(pathSpec) != null)) {
        ctx.delete(pathSpec);
      }
    }
    return ctx.jsonString();
  } catch (Exception ex) {
    throw RESOURCE.invalidInputForJsonRemove(
        input.toString(), Arrays.toString(pathSpecs)).ex();
  }
}
 
Example #22
Source File: JSONArrayTest.java    From JSON-Java-unit-test with Apache License 2.0 6 votes vote down vote up
/**
 * Confirm the creation of a JSONArray from an array of ints
 */
@Test
public void objectArrayVsIsArray() {
    int[] myInts = { 1, 2, 3, 4, 5, 6, 7 };
    Object myObject = myInts;
    JSONArray jsonArray = new JSONArray(myObject);

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString());
    assertTrue("expected 7 top level items", ((List<?>)(JsonPath.read(doc, "$"))).size() == 7);
    assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0")));
    assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1")));
    assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2")));
    assertTrue("expected 4", Integer.valueOf(4).equals(jsonArray.query("/3")));
    assertTrue("expected 5", Integer.valueOf(5).equals(jsonArray.query("/4")));
    assertTrue("expected 6", Integer.valueOf(6).equals(jsonArray.query("/5")));
    assertTrue("expected 7", Integer.valueOf(7).equals(jsonArray.query("/6")));
}
 
Example #23
Source File: AbstractCommentRule.java    From light with Apache License 2.0 6 votes vote down vote up
@Override
public Object map(Object currentValue, Configuration configuration) {
    if(currentValue instanceof Map) {
        ((Map) currentValue).remove("roles");
        ((Map) currentValue).remove("email");
        ((Map) currentValue).remove("credential");
        ((Map) currentValue).remove("createDate");
        ((Map) currentValue).remove("host");
        ((Map) currentValue).remove("out_Create");
        ((Map) currentValue).remove("out_Update");
        ((Map) currentValue).remove("out_ReportSpam");
        ((Map) currentValue).remove("out_UpVote");
        ((Map) currentValue).remove("out_DownVote");
        String rid = (String)((Map) currentValue).get("@rid");
        if(userMap.get(rid) == null) {
            userMap.put(rid, currentValue);
        }
    } else if(currentValue instanceof String) {
        currentValue = userMap.get((String)currentValue);
    }
    return currentValue;
}
 
Example #24
Source File: JsonFormat.java    From koupler with MIT License 5 votes vote down vote up
@Override
public String getPartitionKey(String event) {
    if (event.trim().length() == 0) {
        return null;
    }

    Object jsonEvent = Configuration.defaultConfiguration().jsonProvider().parse(event);
    return JsonPath.read(jsonEvent, partitionKeyField);
}
 
Example #25
Source File: JsonUtils.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
public static DocumentContext toJsonPath(Object object) {
	Configuration configuration = Configuration.builder()
			.jsonProvider(new JacksonJsonProvider())
			.mappingProvider(new JacksonMappingProvider())
			.build();

	return JsonPath.parse(toJson(object), configuration);
}
 
Example #26
Source File: JSONArrayTest.java    From JSON-Java-unit-test with Apache License 2.0 5 votes vote down vote up
/**
 * Exercise JSONArray.join() by converting a JSONArray into a 
 * comma-separated string. Since this is very nearly a JSON document,
 * array braces are added to the beginning and end prior to validation.
 */
@Test
public void join() {
    JSONArray jsonArray = new JSONArray(this.arrayStr);
    String joinStr = jsonArray.join(",");

    // validate JSON
    /**
     * Don't need to remake the JSONArray to perform the parsing
     */
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse("["+joinStr+"]");
    assertTrue("expected 13 items in top level object", ((List<?>)(JsonPath.read(doc, "$"))).size() == 13);
    assertTrue("expected true", Boolean.TRUE.equals(jsonArray.query("/0")));
    assertTrue("expected false", Boolean.FALSE.equals(jsonArray.query("/1")));
    assertTrue("expected \"true\"", "true".equals(jsonArray.query("/2")));
    assertTrue("expected \"false\"", "false".equals(jsonArray.query("/3")));
    assertTrue("expected hello", "hello".equals(jsonArray.query("/4")));
    assertTrue("expected 0.002345", Double.valueOf(0.002345).equals(jsonArray.query("/5")));
    assertTrue("expected \"23.45\"", "23.45".equals(jsonArray.query("/6")));
    assertTrue("expected 42", Integer.valueOf(42).equals(jsonArray.query("/7")));
    assertTrue("expected \"43\"", "43".equals(jsonArray.query("/8")));
    assertTrue("expected 1 item in [9]", ((List<?>)(JsonPath.read(doc, "$[9]"))).size() == 1);
    assertTrue("expected world", "world".equals(jsonArray.query("/9/0")));
    assertTrue("expected 4 items in [10]", ((Map<?,?>)(JsonPath.read(doc, "$[10]"))).size() == 4);
    assertTrue("expected value1", "value1".equals(jsonArray.query("/10/key1")));
    assertTrue("expected value2", "value2".equals(jsonArray.query("/10/key2")));
    assertTrue("expected value3", "value3".equals(jsonArray.query("/10/key3")));
    assertTrue("expected value4", "value4".equals(jsonArray.query("/10/key4")));
    assertTrue("expected 0", Integer.valueOf(0).equals(jsonArray.query("/11")));
    assertTrue("expected \"-1\"", "-1".equals(jsonArray.query("/12")));
}
 
Example #27
Source File: JsonPathSelector.java    From camunda-bpm-reactor with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T map(Object source, TypeRef<T> targetType, Configuration configuration) {
  if (targetType.getType() instanceof Class) {
    return mapper.convertValue(source, (Class<T>) targetType.getType());
  } else {
    throw new IllegalArgumentException("Cannot convert to " + targetType);
  }
}
 
Example #28
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 5 votes vote down vote up
/**
 * Confirm that https://github.com/douglascrockford/JSON-java/issues/167 is fixed.
 * The following code was throwing a ClassCastException in the 
 * JSONObject(Map<String, Object>) constructor
 */
@SuppressWarnings("boxing")
@Test
public void valueToStringConfirmException() {
    Map<Integer, String> myMap = new HashMap<Integer, String>();
    myMap.put(1,  "myValue");
    // this is the test, it should not throw an exception
    String str = JSONObject.valueToString(myMap);
    // confirm result, just in case
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(str);
    assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
    assertTrue("expected myValue", "myValue".equals(JsonPath.read(doc, "$.1")));
}
 
Example #29
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 5 votes vote down vote up
/**
 * Explores how JSONObject handles maps. Insert a string/string map
 * as a value in a JSONObject. It will remain a map. Convert the 
 * JSONObject to string, then create a new JSONObject from the string. 
 * In the new JSONObject, the value will be stored as a nested JSONObject.
 * Confirm that map and nested JSONObject have the same contents.
 */
@Test
public void jsonObjectToStringSuppressWarningOnCastToMap() {
    JSONObject jsonObject = new JSONObject();
    Map<String, String> map = new HashMap<>();
    map.put("abc", "def");
    jsonObject.put("key", map);

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
    assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
    assertTrue("expected 1 key item", ((Map<?,?>)(JsonPath.read(doc, "$.key"))).size() == 1);
    assertTrue("expected def", "def".equals(jsonObject.query("/key/abc")));
}
 
Example #30
Source File: JSONObjectTest.java    From JSON-Java-unit-test with Apache License 2.0 5 votes vote down vote up
/**
 * Explores how JSONObject handles collections. Insert a string collection
 * as a value in a JSONObject. It will remain a collection. Convert the 
 * JSONObject to string, then create a new JSONObject from the string. 
 * In the new JSONObject, the value will be stored as a nested JSONArray.
 * Confirm that collection and nested JSONArray have the same contents.
 */
@Test
public void jsonObjectToStringSuppressWarningOnCastToCollection() {
    JSONObject jsonObject = new JSONObject();
    Collection<String> collection = new ArrayList<String>();
    collection.add("abc");
    // ArrayList will be added as an object
    jsonObject.put("key", collection);

    // validate JSON
    Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString());
    assertTrue("expected 1 top level item", ((Map<?,?>)(JsonPath.read(doc, "$"))).size() == 1);
    assertTrue("expected 1 key item", ((List<?>)(JsonPath.read(doc, "$.key"))).size() == 1);
    assertTrue("expected abc", "abc".equals(jsonObject.query("/key/0")));
}