What is the best way to extract data from a JSON file using Java?

I am working with a JavaScript file that contains the following object:

var MoceanSettings={
       BannerURL:'',
       IsDirectWall:true,
       AppOfDayZone:156431,
       ImpressTrackUrl:null,
       ClickTrackUrl:null,
       Categories:[
          {name:'App Gallery', Zone_T:165294,Zone_M:165295,Zone_B:165296},
          {name:'Entertainment', Zone_T:165306,Zone_M:165307,Zone_B:165308},
          {name:'Games', Zone_T:165297,Zone_M:165298,Zone_B:165299},
          {name:'Lifestyle', Zone_T:165309,Zone_M:165310,Zone_B:165311},
          {name:'Productivity', Zone_T:165303,Zone_M:165304,Zone_B:165305},
          {name:'Travel', Zone_T:165300,Zone_M:165301,Zone_B:165302},
          {name:'Favorites', Zone_T:156431,Zone_M:156431,Zone_B:156431}
       ]
}

I want to use java to parse this file into an object or array. My knowledge of JavaScript and json is quite limited.

Answer №1

Here is an example of how you could achieve this:

import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class ExecuteScript {

    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        engine.eval(new InputStreamReader(ExecuteScript.class.getResourceAsStream("javascript.js")));
    printJSElement("root", engine.get("MoceanSettings"));
    }

    private static void printJSElement(String propName, Object element) {
        if (element instanceof List) {
            printJSList(propName, (List<Object>) element);
        } else if (element instanceof Map) {
            printJSMap(propName, (Map<Object, Object>) element);
        } else {
            printJSProperty(propName, element);
        }
    }

    private static void printJSMap(String propName, Map<Object,Object> objectMap) {
        for (Entry<Object,Object> entry : objectMap.entrySet()) {
            printJSElement(propName + "." + String.valueOf(entry.getKey()), entry.getValue());
        }
    }

    private static void printJSList(String propName, List<Object> objectList) {
        for (int i = 0; i < objectList.size(); i++) {
            printJSElement(propName + "[" + i + "]", objectList.get(i));
        }
    }

    private static void printJSProperty(String propName, Object value) {
        System.out.println(propName + " = " + value);
    }

}

The output will look like this:

root.BannerURL = 
root.IsDirectWall = true
root.AppOfDayZone = 156431
root.ImpressTrackUrl = null
root.ClickTrackUrl = null
root.Categories[0].name = App Gallery
root.Categories[0].Zone_T = 165294
root.Categories[0].Zone_M = 165295
root.Categories[0].Zone_B = 165296
root.Categories[1].name = Entertainment
root.Categories[1].Zone_T = 165306
root.Categories[1].Zone_M = 165307
root.Categories[1].Zone_B = 165308
root.Categories[2].name = Games
root.Categories[2].Zone_T = 165297
root.Categories[2].Zone_M = 165298
root.Categories[2].Zone_B = 165299
root.Categories[3].name = Lifestyle
root.Categories[3].Zone_T = 165309
root.Categories[3].Zone_M = 165310
root.Categories[3].Zone_B = 165311
root.Categories[4].name = Productivity
root.Categories[4].Zone_T = 165303
root.Categories[4].Zone_M = 165304
root.Categories[4].Zone_B = 165305
root.Categories[5].name = Travel
root.Categories[5].Zone_T = 165300
root.Categories[5].Zone_M = 165301
root.Categories[5].Zone_B = 165302
root.Categories[6].name = Favorites
root.Categories[6].Zone_T = 156431
root.Categories[6].Zone_M = 156431
root.Categories[6].Zone_B = 156431

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

Sort Messages By Date Created

While using Vue, I encountered a general JavaScript question. I am fetching cat messages from an API for a chat interface. The initial call returns an array of objects where each object represents a chat message: data: [ {id: 1, created_at: "2022-05 ...

How do I retrieve specific JSON elements from the Response.Body in Scalaj-Http when using HttpRequest and receiving HttpResponse[string]?

I am looking to tally the language tags found in Github repositories, and I'm utilizing scalaj-http for this task. val response: HttpResponse[String] = Http("https://api.github.com/search/repositories?q=size:>=0").asString val b ...

Font in Three JS not loading properly

I'm attempting to use TextGeometry in my project to incorporate text. var shape = new THREE.TextGeometry( 'Hello, World!', { size: 60, height: 20, curveSegments: 3, font: 'helvetiker', weight: ' ...

Having trouble combining several classes in Extent Report while using Selenium with Java

I am facing an issue with merging multiple test cases from different classes into a single extent report. Although all the test cases are executing successfully, they are not being added to my extent report. The Extent Report version I am using is 2.41.2 ...

Handling Exceptions and Terminating the System

I crafted a unique UncaughtExceptionHandler that is designed to display the exception on the console and gracefully shut down the application with a specific exit code. Here's what the class looks like: public class FatalUncaughtExceptionHandler impl ...

Tips for utilizing a shared controller in an Angular Material popup dialogue

Within my project, Angular Material is being used for various dialogs, primarily for alert purposes. However, I now find myself in need of a more complex dialog. The example provided on the Angular Material site showcases how to create a dialog: function ...

Is there a way to exclude a specific div based on two select choices?

Check out my Fiddle demonstration here $('select#classes').on('change', function() { var selectedClass = $(this).val(); $('.col-sm-6:not(:contains(' + selectedClass + '))').hide(); $('select#subjec ...

The import specifier "Nuxt 3 package #internal/nitro" is not recognized

After attempting to upgrade Nuxt.js to the latest version using the command: npx nuxi init nuxt-app I successfully ran and tested a project in Nuxt 3. However, upon running the following command: npm run generate An error message was displayed: ERROR ...

Develop a personalized event using JavaScript and activate it

I have encountered a problem with a Google ad that expands on click and closes when the close button is hit. However, due to changing conditions, I now need it to expand first and then automatically close after a certain time. Additionally, every time it e ...

Eliminating unique phrases from text fields or content sections with the help of jQuery or JavaScript

I'm currently working on a PHP website and have been tasked with the responsibility of removing certain special strings such as phone numbers, email addresses, Facebook addresses, etc. from a textarea that users input data into. My goal is to be able ...

The Service Worker seems to be neglecting to serve the sub-pages at

I've successfully implemented a service worker on my website. The home page loads correctly from the Service Worker cache, and when I visit previously viewed 'posts' while online in Chrome, they load and show as 'from ServiceWorker&apos ...

Strange behavior encountered when using a for...of loop

While experimenting with dynamic route assignment in Express, I encountered some unexpected behavior when using a for...of loop. My original idea was simple: Create an array: const roomsArray = ["Algebra", "Backend", "Frontend"]; Loop through the arr ...

The conventional method of parsing streamed Json data in Java

Is there a method in Java to read/write Json streams without relying on Gson, Jackson, or other json parsers? Currently, I have a file structured like this: file.conf: 01={"string":"Test","number":25,"array":[1,2,3],"object":{"property":"Jack","subobj":{ ...

Changing a number from 0 to 1 in a field using AngularJS (HTML5)

It's strange behavior. I am using an input field with the type set to number. When I enter 1230, the model value remains as 1230. However, when I type 01, it becomes 1. Even though I can see 01 in the input value, there seems to be something relate ...

Creating secure encryption using Jasypt: A step-by-step guide

Upon visiting jasypt.org and reading the question "Can I decrypt an encrypted password?", it is stated here that, if you have encrypted a password using a message digesting technique as recommended (such as by using a PasswordEncryptor implementation, Stan ...

The data type for JSON writing is not valid (NSConcreteMutableData)

My attempt to send a JSON request using AFNetworking is resulting in an error indicating that the JSON text did not start with array or object and option to allow fragments not set: NSString *post = [[NSString alloc] initWithFormat: @"{& ...

Locate the parent element that has the smallest amount of space taken up by its child elements

My goal is to determine which container, among several <divs>, each containing multiple child <divs> of varying sizes, has the smallest amount of space covered by the child elements. <div class="container" id="first"> ...

Avoiding data type conversion in JavaScript/TypeScript

Currently delving into the world of JavaScript, I come from a background of working with statically typed languages. Naturally, I opted to dive into TypeScript instead of starting directly with JS. While TypeScript is great and addresses many issues presen ...

Error: Attempting to access the 'clipboard' property on an undefined object results in a TypeError when invoking this.$q.electron.clipboard

I'm currently working on incorporating copy to clipboard functionality into my app using Electron. This is the command I am using: methods: { copyToClipboard () { if (process.env.MODE === 'electron') { this.$q.electro ...

Manipulate Images Efficiently with jQuery

Are there any jQuery plugins or JavaScript controls available that can display an array of images, with the option to delete an image based on user action? For example, something similar to this: , but with a dedicated delete button on each image. One ad ...