Instead of using the split function, you can convert your String to a JSONArray and then iterate throw the array

JSONArray jsonArray = new JSONArray(response.toString());
for(int i=0; i<jsonArray.length(); i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    String jsonObjectAsString = jsonObject.toString();
}
Answer from ThomasThiebaud on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 40113132 › how-to-split-a-json-array
java - How to split a json array - Stack Overflow
JSONArray profiles = new JSONArray(); JSONObject profile1 = new JSONObject(); profile1.put("Name", "Roger"); profile1.put("Age", "Twenty"); JSONObject profile2 = new JSONObject(); profile2.put("Name", "Roger"); profile2.put("Age", "Twenty"); profiles.add(profile1); profiles.add(profile2); ... Sign up to request clarification or add additional context in comments.
Top answer
1 of 2
4

You can use subList method:

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class JsonApp {

    public static void main(String[] args) {
        List<Integer> ints = IntStream.range(1, 10).boxed().collect(Collectors.toList());
        JsonArrayExt array = new JsonArrayExt(ints);

        JsonArray array1 = array.subList(2, 5);
        System.out.println(array);
        System.out.println(array1);
    }
}

class JsonArrayExt {
    private final JsonArray array;

    public JsonArrayExt(List<Integer> ints) {
        this(Json.createArrayBuilder(ints).build());
    }

    public JsonArrayExt(JsonArray array) {
        this.array = Objects.requireNonNull(array);
    }

    public JsonArray subList(int fromIndex, int toIndex) {
        JsonArrayBuilder builder = Json.createArrayBuilder();
        array.subList(fromIndex, toIndex).forEach(builder::add);

        return builder.build();
    }

    @Override
    public String toString() {
        return array.toString();
    }
}

Above code prints:

[1,2,3,4,5,6,7,8,9]
[3,4,5]
2 of 2
2

with Gson

List<MyModel> myModelList = gson.fromJson(jsonArray.toString(), listType);

Updated

you can create a utility for the same if you only want to use javax.json package. Below is the complete sample code with only javax.json.* package.

import java.io.StringReader; import java.util.List;

import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonValue;

public class Converter {
    public static void main(String[] args) {
        String str =     "{\r\n" + 
                         "\"name\":\"John\",\r\n" + 
                         "\"age\":30,\r\n" + 
                         "\"cars\":[ \"Ford\", \"BMW\", \"Fiat\" ]\r\n" + 
                         "}";

        JsonReader reader = Json.createReader(new StringReader(str));
        JsonObject object = reader.readObject();
        JsonArray array = object.getJsonArray("cars");
        System.out.println(getJsonArrayFromIndex(1, 2, array));
        System.out.println(getJsonArrayFromIndex(0, 2, array));
        System.out.println(getJsonArrayFromIndex(0, 1, array));
    }

    public static List<JsonValue> getJsonArrayFromIndex(int start, int end, JsonArray array) {
        return array.subList(start, end);       
    }
}

output

[BMW]
[Ford, BMW]
[Ford]
🌐
Quora
quora.com › How-do-I-split-a-single-JSON-object-array-into-two-JSON-arrays
How to split a single JSON object array into two JSON arrays - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
Top answer
1 of 3
2

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;
}
2 of 3
1

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);
    }
}
🌐
Quora
quora.com › How-do-I-split-the-key-and-value-from-the-JSON-array-using-the-Java-language
How to split the key and value from the JSON array using the Java language - Quora
Answer (1 of 2): If the JSONArray is holding JSONObjects then for every ith element (.getJSONObject(i)) its key set can be extracted and used to retrieve the corresponding value from the json object. Something like this [code]JSONObject jsonBody = new JSONObject("{\"name1\":\"sss\"}"); JSONArr...
🌐
Stack Overflow
stackoverflow.com › questions › 43520156 › split-all-array-elements-from-json-in-java
split all array elements from json in java - Stack Overflow
CopyString serverResponse = "YOUR STRING"; JSONArray serverJsonArray = new JSONArray(serverResponse); ... CopyArrayList<String> products = new ArrayList<>(serverJsonArray.length()); for(int i = 0; i < serverJsonArray.length(); i++){ products.add(serverJsonArray.getString(i)); } ... CopyString[] products = new String[serverJsonArray.length()]; for(int i = 0; i < serverJsonArray.length(); i++){ products[i] = serverJsonArray.getString(i); } ... Find the answer to your question by asking.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 41245621 › string-split-for-json-array
java - String.split for JSON array - Stack Overflow
May 24, 2017 - You could use JsonArray to get those two Objects into nice array which then can be iterated. ... If that is what is inside the String then NO. ... String[] splitTextObject = YOUR_STRING.split(", "); String object1 = splitTextObject[0]; String object2 = splitTextObject[1]; ...
🌐
Stack Overflow
stackoverflow.com › questions › 49750548 › split-array-nested-in-json-with-java
split array nested in json with java - Stack Overflow
April 10, 2018 - You can solve it using almost any available JSON parsing library. For example I will do it with Jackson. You most probably already have data classes (POJOs) for your entries. That's my view of such hierarchy ... import java.util.Date; public abstract class BaseDataView { protected String key; protected Date date; // public get/set }
Top answer
1 of 1
3

When processing huge input files, you should use a streaming approach instead of loading the whole document into memory, to reduce memory footprint, avoid OutOfMemoryError, and make it possible to start processing whie reading input. JSONArray has little support for streaming, so I would recommend looking into Jackson's streaming API, GSON streaming, or similar.

That being said, if you insist on using JSONArray, you can cobble together a streaming method by using JSONTokener. Here's a sample program that will stream an input file and create separate JSON documents with at most 10 elements each.

import java.io.*;
import java.util.*;
import org.json.*;

public class JsonSplit {

    private static final int BATCH_SIZE = 10;

    public static void flushFile(List<Object> objects, int d) throws Exception {
        try (FileOutputStream output = new FileOutputStream("split-" + d
            + ".json");
                Writer writer = new OutputStreamWriter(output, "UTF-8")) {
            JSONArray jsonArray = new JSONArray(objects);
            jsonArray.write(writer);
        }
    }

    public static void main(String[] args) throws Exception {
        int outputIndex = 0;
        try (InputStream input = new BufferedInputStream(
                new FileInputStream(args[0]))) {
            JSONTokener tokener = new JSONTokener(input);
            if (tokener.nextClean() != '[') {
                throw tokener.syntaxError("Expected start of JSON array");
            }
            List<Object> jsonObjects = new ArrayList<>();
            while (tokener.nextClean() != ']') {
                // Back up one character, it's part of the next value.
                tokener.back();
                // Read the next value in the array.
                jsonObjects.add(tokener.nextValue());
                // Flush if max objects per file has been reached.
                if (jsonObjects.size() == BATCH_SIZE) {
                    flushFile(jsonObjects, outputIndex);
                    jsonObjects.clear();
                    outputIndex++;
                }
                // Read and discard commas between array elements.
                if (tokener.nextClean() != ',') {
                    tokener.back();
                }
            }
            if (!jsonObjects.isEmpty()) {
                flushFile(jsonObjects, outputIndex);
            }
            // Verify that end of input is reached.
            if (tokener.nextClean() != 0) {
                throw tokener.syntaxError("Expected end of document");
            }
        }

    }

}

To see why a streaming approach is needed for huge files, download or create a huge JSON file, then try running a naive implementation that doesn't stream. Here's a Perl command to create a JSON array with 1,000,000 elements and a file size of around 16 MB.

perl -le 'print "["; for (1..1_000_000) {print "," unless $_ == 1; print "{\"id\": " . int(rand(1_000_000)) . "}";} print "]"' > input_huge.json

If you run JsonSplit on this input, it will churn away happily with a small memory footprint, producing 100,000 files with 10 elements in each. Also, it will begin producing output files immediately when started.

If, instead, you run the following JsonSplitNaive program, which reads the entire JSON document in one go, it will apparently do nothing for a long period, then abort with an OutOfMemoryError.

import java.io.*;
import java.util.*;
import org.json.*;

public class JsonSplitNaive {

    /*
     * Naive version - do not use, will fail with OutOfMemoryError for
     * huge inputs.
     */

    private static final int BATCH_SIZE = 10;

    public static void flushFile(List<Object> objects, int d) throws Exception {
        try (FileOutputStream output = new FileOutputStream("split-" + d
            + ".json");
                Writer writer = new OutputStreamWriter(output, "UTF-8")) {
            JSONArray jsonArray = new JSONArray(objects);
            jsonArray.write(writer);
        }
    }

    public static void main(String[] args) throws Exception {
        int outputIndex = 0;
        try (InputStream input = new BufferedInputStream(
                new FileInputStream(args[0]))) {
            List<Object> jsonObjects = new ArrayList<>();
            JSONArray jsonArray = new JSONArray(new JSONTokener(input));
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObjects.add(jsonArray.get(i));
                // Flush if max objects per file has been reached.
                if (jsonObjects.size() == BATCH_SIZE) {
                    flushFile(jsonObjects, outputIndex);
                    jsonObjects.clear();
                    outputIndex++;
                }
            }
            if (!jsonObjects.isEmpty()) {
                flushFile(jsonObjects, outputIndex);
            }
        }
    }

}
🌐
Coderanch
coderanch.com › t › 681979 › java › Parse-JSON-split-Java
Parse JSON using split in Java (Beginning Java forum at Coderanch)
July 11, 2017 - Pass it to a Scanner constructor and change the delimiter as you go. Or create a regex for \{\"|\"}|\":\"|\",\" or something like that which will match the different delimiters. Use the Scanner.nextXXX methods or String#split with such a regex. ... Knute Snortum wrote:I think the easiest way is to use JSONObject: .
🌐
Stack Overflow
stackoverflow.com › questions › 16509165 › split-json-object
java - Split JSON Object - Stack Overflow
May 22, 2017 - I'm working on a D3 DPS calculator and i'm having a problem with a JSON-Object. I get a JSON-Object like this: {"Sockets":{"min":1,"max":1}, "Dexterity_Item":{"min":165,"max":165}, "Durability_Cur...
🌐
Stack Overflow
stackoverflow.com › questions › 55191982 › how-to-split-a-json-string-to-two-json-objects-in-java
How to Split a JSON string to two JSON objects in Java - Stack Overflow
3 split json object from json array in java · 3 Cut the json string in to two different json string in java · 2 Splitting JSON string into multiple JSON strings in Java · 1 Splitting in Java or using JSON · 2 Split String json · 2 Split a JsonArray · Why Is the Dual Basis Mathematically Unavoidable?
🌐
JSON Utils
jsonutils.org › home › json tools › json array splitter
JSON Array Splitter - Split Large JSON Arrays | JSON Utils
The tool automatically adds numbers or field values to create unique names (e.g., "mydata_1.json", "mydata_2.json"). By default, the "Preserve original order" option maintains the sequence of items from your original array. Uncheck this if order doesn't matter for your use case. Yes! Each chunk has a preview button (👁️) that opens the chunk content in a new window.
Top answer
1 of 2
1

You could do something like this:

public static void main(String[] args) throws IOException {

    String summary = "";

    for(int a = 0; a<100000; a++) { 
        String current =  "\r\n" + new ObjectMapper().writeValueAsString(new MyClass());

        if((summary + current).getBytes("UTF-8").length>100000) {
            System.out.println("Overload 100 kb!");
             printFile(summary);
            summary = current;
        }
        else 
            summary = summary + "\r\n" + new ObjectMapper().writeValueAsString(new MyClass());
    } 
}

public static void printFile(String string) throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_SSS"); 
    try(  PrintWriter out = new PrintWriter("C:\\Chunks\\" +sdf.format(new Date()) +".txt" )  ){
        out.println( string );
    }
}

Consider UTF-8 as a choice. Split happens taking count the byte[] lenght so 100000 byte are 100kb.

For the serialization I've used a standard Jackson approach, this is the maven dependency:

   <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.3</version>
</dependency>

...and finally the simple Pojo class:

public class MyClass implements Serializable{


    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public String getField1() {
        return field1;
    }
    public void setField1(String field1) {
        this.field1 = field1;
    }
    public String getField2() {
        return field2;
    }
    public void setField2(String field2) {
        this.field2 = field2;
    }
    public MyClass() {
        super();
        // TODO Auto-generated constructor stub
    }
    private String field1;
    private String field2;
    //getter and setter
}

Let me know if it helps!

2 of 2
0

The exact implementation may depend on the serialization framework used (have a look at Jackson, it is pretty easy to use), some may offer a specialized streaming API that can achieve something like this. In the scenario that you are describing, a much simpler solution could be used though:

Serialize each instance in a for-loop and collect Strings in a buffer (e.g. StringBuilder or you go straight to an OutputStream). However, before you append a String to this buffer, you can check if size of your buffer + size of the new String exceed the 100kb. The only piece missing now are a few characters for start ( [ ), separator ( , ) and end ( ] )

(For the size calculations to be correct, you may have to convert the strings to bytes since characters like Äφς will take up more than one byte. Maybe this is already handled by your JSON framework)

You could of course do the serialization manually, but especially if your strings can contain characters like quotes ( " ) you could end up writing a lot of code until the JSON format is correct.

[edith: as others have pointed out, if the strings could be longer than 100kb it is not really possible to follow the specification]