Search in sources :

Example 46 with JSONArray

use of net.minidev.json.JSONArray in project json-android-compare by martinadamek.

the class SmartJson method parsePublicTimeline.

public List<Map> parsePublicTimeline(InputStream inputStream) {
    List<Map> result = new ArrayList<Map>();
    JSONParser p = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
    try {
        Map map;
        Set keys;
        Set keys2;
        JSONObject user;
        JSONObject jsonObject;
        JSONArray jsonArray = (JSONArray) p.parse(new InputStreamReader(inputStream));
        int size = jsonArray.size();
        for (int i = 0; i < size; i++) {
            map = new HashMap();
            jsonObject = (JSONObject) jsonArray.get(i);
            keys = jsonObject.keySet();
            for (Object key : keys) {
                if ("user".equals(key)) {
                    user = (JSONObject) jsonObject.get(key);
                    keys2 = user.keySet();
                    for (Object key2 : keys2) {
                        map.put("user." + key2, user.get(key2));
                    }
                } else {
                    map.put(key, jsonObject.get(key));
                }
            }
            result.add(map);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
Also used : Set(java.util.Set) JSONObject(net.minidev.json.JSONObject) InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JSONArray(net.minidev.json.JSONArray) JSONParser(net.minidev.json.parser.JSONParser) JSONObject(net.minidev.json.JSONObject) Map(java.util.Map) HashMap(java.util.HashMap)

Example 47 with JSONArray

use of net.minidev.json.JSONArray in project ddf by codice.

the class GeoJsonQueryResponseTransformer method transform.

@Override
public BinaryContent transform(SourceResponse upstreamResponse, Map<String, Serializable> arguments) throws CatalogTransformerException {
    if (upstreamResponse == null) {
        throw new CatalogTransformerException("Cannot transform null " + SourceResponse.class.getName());
    }
    JSONObject rootObject = new JSONObject();
    addNonNullObject(rootObject, "hits", upstreamResponse.getHits());
    JSONArray resultsList = new JSONArray();
    if (upstreamResponse.getResults() != null) {
        for (Result result : upstreamResponse.getResults()) {
            if (result == null) {
                throw new CatalogTransformerException("Cannot transform null " + Result.class.getName());
            }
            resultsList.add(convertToJSON(result));
        }
    }
    addNonNullObject(rootObject, "results", resultsList);
    String jsonText = JSONValue.toJSONString(rootObject);
    return new BinaryContentImpl(new ByteArrayInputStream(jsonText.getBytes(StandardCharsets.UTF_8)), DEFAULT_MIME_TYPE);
}
Also used : JSONObject(net.minidev.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) JSONArray(net.minidev.json.JSONArray) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl) Result(ddf.catalog.data.Result)

Example 48 with JSONArray

use of net.minidev.json.JSONArray in project pentaho-kettle by pentaho.

the class JsonInputTest method testJsonInputPathResolution.

@Test
public void testJsonInputPathResolution() throws KettleException {
    JsonInputField inputField = new JsonInputField("value");
    final String PATH = "$[*].name";
    inputField.setPath(PATH);
    inputField.setType(ValueMetaInterface.TYPE_STRING);
    JsonInputMeta inputMeta = createSimpleMeta("json", inputField);
    VariableSpace variables = new Variables();
    JsonInput jsonInput = null;
    try {
        jsonInput = createJsonInput("json", inputMeta, variables, new Object[] { getSampleJson() });
        JsonInputData data = (JsonInputData) Whitebox.getInternalState(jsonInput, "data");
        FastJsonReader reader = (FastJsonReader) Whitebox.getInternalState(data, "reader");
        RowSet rowset = reader.parse(new ByteArrayInputStream(getSampleJson().getBytes()));
        List results = (List) Whitebox.getInternalState(rowset, "results");
        JSONArray jsonResult = (JSONArray) results.get(0);
        assertEquals(1, jsonResult.size());
        assertEquals("United States of America", jsonResult.get(0));
    } catch (InvalidPathException pathException) {
        assertNull(jsonInput);
    }
}
Also used : VariableSpace(org.pentaho.di.core.variables.VariableSpace) RowSet(org.pentaho.di.core.RowSet) JSONArray(net.minidev.json.JSONArray) ValueMetaString(org.pentaho.di.core.row.value.ValueMetaString) FastJsonReader(org.pentaho.di.trans.steps.jsoninput.reader.FastJsonReader) InvalidPathException(com.jayway.jsonpath.InvalidPathException) Variables(org.pentaho.di.core.variables.Variables) ByteArrayInputStream(java.io.ByteArrayInputStream) FileObject(org.apache.commons.vfs2.FileObject) List(java.util.List) ArrayList(java.util.ArrayList) FileInputList(org.pentaho.di.core.fileinput.FileInputList) Test(org.junit.Test)

Example 49 with JSONArray

use of net.minidev.json.JSONArray in project mica2 by obiba.

the class DocumentDifferenceService method flatten.

public static Map<String, Object> flatten(Object object) throws JsonProcessingException {
    Map<String, Object> map = new RegexHashMap();
    if (object == null)
        return map;
    final String string = mapper.writeValueAsString(object);
    JSONArray array = JsonPath.using(Configuration.builder().options(Option.AS_PATH_LIST).build()).parse(string).read("$..*");
    array.stream().map(Object::toString).filter(key -> !key.startsWith("$['logo']") && !key.startsWith("$['createdDate']") && !key.startsWith("$['lastModifiedDate']") && !key.startsWith("$['membershipSortOrder']")).forEach(key -> {
        Object read = JsonPath.parse(string).read(key);
        if (read != null && !(read instanceof Map) && !(read instanceof List)) {
            String processedKey = key.replaceAll("(\\$\\[')|('\\])", "").replaceAll("(\\[')", ".");
            map.put(processedKey, read);
        }
    });
    return map;
}
Also used : Arrays(java.util.Arrays) ValueDifference(com.google.common.collect.MapDifference.ValueDifference) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashMap(java.util.HashMap) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Option(com.jayway.jsonpath.Option) JsonPath(com.jayway.jsonpath.JsonPath) Maps(com.google.common.collect.Maps) MapDifference(com.google.common.collect.MapDifference) List(java.util.List) Configuration(com.jayway.jsonpath.Configuration) JSONArray(net.minidev.json.JSONArray) Map(java.util.Map) RegexHashMap(org.obiba.mica.core.support.RegexHashMap) RegexHashMap(org.obiba.mica.core.support.RegexHashMap) JSONArray(net.minidev.json.JSONArray) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) RegexHashMap(org.obiba.mica.core.support.RegexHashMap)

Example 50 with JSONArray

use of net.minidev.json.JSONArray in project mica2 by obiba.

the class EntityConfigKeyTranslationService method getTranslationMap.

private RegexHashMap getTranslationMap(EntityConfig config, String prefix) {
    String string = config.getSchema();
    JSONArray normalArray = JsonPath.using(Configuration.builder().options(Option.AS_PATH_LIST, Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS).build()).parse(string).read("$..*");
    JSONArray itemsArray = JsonPath.using(Configuration.builder().options(Option.AS_PATH_LIST, Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS).build()).parse(string).read("$..items");
    RegexHashMap map = new RegexHashMap();
    String joinedLocales = getJoinedLocales();
    normalArray.stream().map(Object::toString).filter(key -> key.endsWith("['title']")).forEach(key -> {
        Object read = JsonPath.parse(string).read(key);
        if (read != null) {
            String cleanKey = key.replaceAll("(\\$\\[')|('\\])", "").replaceAll("(\\[')", ".").replaceAll("\\.title$", "").replaceAll("^properties\\.", "").replaceAll("\\.properties", "");
            String processedKey = (cleanKey.startsWith("_") ? prefix : prefix + "model\\.") + Pattern.quote((cleanKey.startsWith("_") ? cleanKey.substring(1) : cleanKey)) + "(\\[\\d+\\])?" + "(" + joinedLocales + ")?";
            map.put(processedKey, read.toString());
        }
    });
    itemsArray.stream().map(Object::toString).forEach(itemkey -> {
        Object read = JsonPath.parse(string).read(itemkey);
        if (read != null && read instanceof List) {
            JSONArray array = (JSONArray) read;
            array.forEach(arrayItem -> {
                if (arrayItem != null && arrayItem instanceof Map) {
                    Map itemMap = (Map) arrayItem;
                    Object key = itemMap.get("key");
                    Object name = itemMap.get("name");
                    String cleanKey = itemkey.replaceAll("(\\$\\[')|('\\])", "").replaceAll("(\\[')", ".").replaceAll("\\.items$", "").replaceAll("^properties\\.", "").replaceAll("\\.properties", "") + "." + key.toString();
                    String processedKey = (cleanKey.startsWith("_") ? prefix : prefix + "model\\.") + Pattern.quote((cleanKey.startsWith("_") ? cleanKey.substring(1) : cleanKey));
                    map.put(processedKey, name);
                }
            });
        }
    });
    return map;
}
Also used : JsonTranslator(org.obiba.core.translator.JsonTranslator) Arrays(java.util.Arrays) PrefixedValueTranslator(org.obiba.core.translator.PrefixedValueTranslator) StudyDatasetConfig(org.obiba.mica.micaConfig.domain.StudyDatasetConfig) HashMap(java.util.HashMap) PopulationConfig(org.obiba.mica.micaConfig.domain.PopulationConfig) Inject(javax.inject.Inject) HarmonizationPopulationConfig(org.obiba.mica.micaConfig.domain.HarmonizationPopulationConfig) StudyConfig(org.obiba.mica.micaConfig.domain.StudyConfig) HarmonizationStudyConfig(org.obiba.mica.micaConfig.domain.HarmonizationStudyConfig) Configuration(com.jayway.jsonpath.Configuration) Map(java.util.Map) RegexHashMap(org.obiba.mica.core.support.RegexHashMap) Translator(org.obiba.core.translator.Translator) ProjectConfig(org.obiba.mica.micaConfig.domain.ProjectConfig) HarmonizationDatasetConfig(org.obiba.mica.micaConfig.domain.HarmonizationDatasetConfig) DataCollectionEventConfig(org.obiba.mica.micaConfig.domain.DataCollectionEventConfig) EntityConfig(org.obiba.mica.micaConfig.domain.EntityConfig) Option(com.jayway.jsonpath.Option) JsonPath(com.jayway.jsonpath.JsonPath) Collectors(java.util.stream.Collectors) TranslationUtils(org.obiba.core.translator.TranslationUtils) List(java.util.List) Component(org.springframework.stereotype.Component) JSONArray(net.minidev.json.JSONArray) Optional(java.util.Optional) NetworkConfig(org.obiba.mica.micaConfig.domain.NetworkConfig) Pattern(java.util.regex.Pattern) RegexHashMap(org.obiba.mica.core.support.RegexHashMap) JSONArray(net.minidev.json.JSONArray) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) RegexHashMap(org.obiba.mica.core.support.RegexHashMap)

Aggregations

JSONArray (net.minidev.json.JSONArray)71 JSONObject (net.minidev.json.JSONObject)52 Test (org.junit.Test)13 HashMap (java.util.HashMap)10 JSONParser (net.minidev.json.parser.JSONParser)10 ArrayList (java.util.ArrayList)9 Map (java.util.Map)9 HashSet (java.util.HashSet)6 List (java.util.List)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 JSONConverterException (org.btrplace.json.JSONConverterException)5 Test (org.testng.annotations.Test)5 DocumentContext (com.jayway.jsonpath.DocumentContext)3 JsonPath (com.jayway.jsonpath.JsonPath)3 Option (com.jayway.jsonpath.Option)3 ContentType (ddf.catalog.data.ContentType)3 SourceInfoResponse (ddf.catalog.operation.SourceInfoResponse)3 SourceInfoRequestEnterprise (ddf.catalog.operation.impl.SourceInfoRequestEnterprise)3 SourceDescriptor (ddf.catalog.source.SourceDescriptor)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3