简体   繁体   中英

How to split json array into strings?

I have a String with a json array consisting of objects, like this:

 [{..},{..}, ...]

I want to extract each object inside this array as strings. Array length is unknown and objects are arbitrary.

A naive approach might be to simply split on "},{" , but it's not gonna work in practice. Of course, I can deserialize the string to a Java array of objects and then serialize each object to string, but that is not safe because the final output might no longer be be byte-for-byte exact the input (which is a requirement. Also, performance might be a problem).

Any ideas?

Well, I'm a little ashamed to post this code. It's not optimal at all, looks awful, but probably it could lead you to right direction if you want completely unaltered content.

enum ParserState {
    READING_OBJECT,
    READING_ARRAY
}


public static List<String> extractObjects(String array) throws ParseException {
    ParserState state = ParserState.READING_ARRAY;
    ArrayList<String> result = new ArrayList<String>();
    StringBuilder currentObject = null;
    int i = 0;
    int parenthesisBalance = 0;
    for (char c : array.toCharArray()) {
        switch (c) {
            case '{': {
                if (state == ParserState.READING_ARRAY) {
                    state = ParserState.READING_OBJECT;
                    currentObject = new StringBuilder();
                }
                parenthesisBalance++;
                currentObject.append(c);
                break;
            }
            case '}': {
                if (state == ParserState.READING_ARRAY) {
                    throw new ParseException("unexpected '}'", i);
                } else {
                    currentObject.append(c);
                    parenthesisBalance--;
                    if (parenthesisBalance == 0) {
                        state = ParserState.READING_ARRAY;
                        result.add(currentObject.toString());
                    }
                }
                break;
            }
            default: {
                if (state == ParserState.READING_OBJECT) {
                    currentObject.append(c);
                }
            }
        }
        i++;
    }
    return result;
}

Try the code below using GSON Lib - you can put json objects also instead of string LOCATION

public static void main(String[] args) {
    String obj = "{'id':'joe','ts':'2014-12-02T13:58:23.801+0100','foo':{'bar':{'v1':50019820,'v2':0,     'v3':0.001, 'v4':-100, 'v5':0.000001, 'v6':0.0, 'b':true}}}".replace("'", "\"");
    String string = String.format("[%s,%s,%s,%s]", obj , obj , obj , obj );

    JsonParser parser = new JsonParser();
    JsonArray arr = (JsonArray)parser.parse(string);

    //JsonArray arr = o.getAsJsonArray();
    Iterator<JsonElement> itr  = arr.iterator();
    while(itr.hasNext()){
        JsonElement val = itr.next();
        System.out.println(val);
    }
}

Try this code:

public List<String> split(String jsonArray) throws Exception {
        List<String> splittedJsonElements = new ArrayList<String>();
        ObjectMapper jsonMapper = new ObjectMapper();
        JsonNode jsonNode = jsonMapper.readTree(jsonArray);

        if (jsonNode.isArray()) {
            ArrayNode arrayNode = (ArrayNode) jsonNode;
            for (int i = 0; i < arrayNode.size(); i++) {
                JsonNode individualElement = arrayNode.get(i);
                splittedJsonElements.add(individualElement.toString());
            }
        }
        return splittedJsonElements;
}

I used Jackson library.

Hope this helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM