Transferring a collection of files in JSON array format

I have a json object that needs to be uploaded, containing nested arrays with files:

[{"key":"value","key1":"value1"},
[{"innerkey":"innervalue","filename":"name"},{"innerkey":"innervalue","filename":"name"}]]

The two inner keys within the JsonArray represent files that require uploading using okhttp multipart.

To upload a normal field, I simply add it as follows:

multipart.addFormDataPart(key, value);

Adding a file is done like this:

 multipart.addFormDataPart("filename", "image.jpeg", RequestBody.create(MediaType.parse("image/jpeg"), new File(path)));

In the past, I successfully uploaded a non-nested json by converting it into a hashmap and utilizing a for loop to add parts dynamically:

 MultipartBody.Builder multipart = new MultipartBody.Builder();
        for (Map.Entry<String, String> entry : data.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if(!key.equals("filePath")){
                multipart.addFormDataPart(key, value);

            }else{

                String filename = "";
                String type = MyUtility.getMimeType(key);
                filename = key.substring(key.lastIndexOf("/") + 1);
                multipart.addFormDataPart("fileName", filename, RequestBody.create(MediaType.parse(type), new File(key)));
            }
        }

The new nested structure poses some challenges in processing. How can I handle this?

Answer №1

Are you in search of a solution similar to this?

    public static Map<String,String> convertToMap(Object yourJsonArrayOrJsonObject) throws Exception
    {
        HashMap<String, String> map = new HashMap<>();
        processJSON(null, yourJsonArrayOrJsonObject, map);
        return map;
    }

    private static void processJSON(String jsonKey, Object jsonItem, Map<String, String> map)
    {
        if (jsonItem instanceof JSONArray)
        {
            JSONArray array = (JSONArray) jsonItem;
            for (Object arrayItem : array)
            {
                processJSON(null, arrayItem, map);
            }
        } else if (jsonItem instanceof JSONObject)
        {
            JSONObject json = (JSONObject) jsonItem;
            Set<String> keys = json.keySet();
            for (String key : keys)
            {
                processJSON(key, json.get(key), map);
            }
        } else
        {
            map.put(jsonKey, String.valueOf(jsonItem));
        }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

performing nested queries in nodejs using a callback function

Over the course of my research, I've come across numerous examples of one-to-many relations. However, I have yet to find a clear-cut example demonstrating how to solve nested queries for normalized data in 'mongodb'. Perhaps it's just m ...

What is the procedure for iterating through the square brackets of a JSON array?

Here's the data I have: $json_data_array = '[ { "id": 1, "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd7cdffcbdacccb91dcd0d2">[email protected]</a>", ...

What is the method for displaying an object as JSON on the console in Angular2?

I've been utilizing a service to input my form data into an array within my angular2 application. The information is organized in the following manner: arr = [] arr.push({title:name}) After executing console.log(arr), it displays as Object. However, ...

Transforming a JSON into a JavaScript object using deserialization

Within a Java server application, there exists a string that can be accessed through AJAX. The structure of this string is exemplified below: var json = [{ "adjacencies": [ { "nodeTo": "graphnode2", "nodeFrom": "graphnode1" ...

In Python, extract data from the top level of a JSON file

Looking for assistance with parsing a JSON stored as a string: message = """{"info":{"keyVersion":1,"timestamp":"2020-11-05 20:00:00","encryptedData":"75657374696f6e732068617665207265636 ...

Top method for hosting a lone JSON document

After developing a RoR application, I encountered a scenario where a JSON file needed to be created and sent to a server. My concern now is finding the optimal way to host this file so it can be accessed quickly from any location without crashing under h ...

Retrieving data from a WebAPI in JSON format and then storing it in a Store

As I dive into learning ExtJS-4.2, I have been diligently following their MVC tutorial... I successfully constructed my controller, view, model, and store with hardcoded data. Additionally, I have set up a WebAPI for testing purposes which provides result ...

Secure User Verification in Laravel 5 and AngularJs sans the need for JWT Tokens

I am currently working on a project that involves utilizing a Laravel-based back-end and a front-end built with both Laravel and AngularJS. After completing 40% of the back-end development, I am now faced with the task of implementing the front-end. Howev ...

Including a null:null entry in the json_encoded data

The following code was not written by me, and unfortunately I do not have the time to update the deprecated calls. <?php $mageFilename = 'app/Mage.php'; require_once $mageFilename; umask(0); Mage::app(); $db=mysql_connect('localhost&ap ...

Modifying and refreshing a JSON document

I have written a small script to loop through my current Json file, but I am facing an issue when trying to append a key and value pair. Here is the content of my file: [ { "URL": "https://p59-caldav.icloud.com", } ] I want to add a new key-valu ...

Is there a way to transform a JSON dictionary into a Bash one?

Trying to capture output from an AWS CLI command in Bash and use it as input for another command. Managed to store the output in a variable using this helpful response: iid=$(aws ec2 run-instances ...) The output looks like this: { "ImageId": &q ...

What is the best way to combine duplicate JSON objects together?

I am facing a challenge with my json data structure, shown below: [{ "attributeId": 6, "attributeType": "price", "attributeValue": "{10,20,100}", "displayOn": "true", "attributeName": "price" }, { "attributeId": 6, "attribu ...

Streamline JSON Hierarchy

I am working with a script that generates JSON results in the following format: [ [ [ "maturity_date", "12/19/2017" ], [ "interest_rate", 0.22 ], [ "interest_earned", 264 ], [ "manage ...

Combining various animations (tracks) into a unified JSON file for THREE.js from 3DS MAX for seamless export

Exploring the 'Animation / Skinning / Blending' Three.js example, I've encountered a JSON model known as the Marine which houses multiple animation tracks including idle, walk, and run. These animations are stored within an "animations" arra ...

Get a value from a function's completion handler in Swift and assign it to a global variable

Seeking to extract the variable from the competition within a function and transform it into a global variable. Below is the function that is being invoked: func getJsonFromUrl(name: String, completion: @escaping (String?)->()) { // utilize the name va ...

Using Kotlin on the Android platform, learn how to convert a string into a JSON string

Seeking to convert a string into a JSON string using Gson. My desired outcome is to transform "email" into "{"email" : "$email"}" I have the function: fun serializeUserEmail(email: String): String { return &quo ...

What is preventing me from modifying the data in a JSON object?

My task is to update the value "customer.signature", but I am facing an issue with my code. The JSON and HTML seem to be error-free, so the problem lies within my JS code. While "data.signature" updates correctly, "data.customer.signature" does not. The J ...

Utilizing Regular Expressions for JSON data deserialization

I'm having trouble extracting keys and values from JSON data using regular expressions when the JSON contains special characters like \ & ". { "KeyOne":"Value One", "KeyTwo": "Value \\ two", "KeyThree": "Value \" Thre ...

shapeshift.io's API is notifying users of an error, stating that there is either a Output Amount or Deposit Amount missing

When using the shapeshift api and posting to , an error is encountered: "Missing a Output Amount or Deposit Amount". The JSON Request String looks like this: { "returnAddress" : "19z95ce8a1UwV3PCCCBE7AD7hNXENW3gu4", "withdrawal" : "0xFF7c7d21cf668F59A8518 ...

To achieve the desired format, where should I press or manipulate the information?

I need help with manipulating arrays to generate a specific JSON file structure. I've made some progress but got stuck at this point: var T_nn_IN = document.getElementById('datatablenewname'); var tabledata_newname_initialname = []; ...