How can a multi-dimensional object in JavaScript be translated into Java?

I'm working on an Android game and I need to store levels as a static Java class. Can anyone help me convert this Javascript object into Java code?

var Levels = {
Level1:{
    shapes:[
    {
        bodytype : "dynamic",
        h : "50.0000",
        nameid : "hofN7-1",
        props : {
            id : "properties"
        },
        rotation : "0.0000",
        type : "square",
        uid : "Av2EZQh",
        w : "50.0000",
        x : "20.0000",
        y : "20.0000"
    },
    {
        bodytype : "dynamic",
        h : "50.0000",
        nameid : "hofN7-2",
        props : {
            gravMassScale : "2",
            id : "properties",
            inertia : "2",
            isBullet : true,
            torque : "2",
            velocity : {
                x : "2",
                y : "2"
            }
        }
    }
...

Answer №1

For those seeking a structure similar to how JavaScript stores objects, consider using the JSONObject class:

Explore this link for more information: http://json.org/javadoc/org/json/JSONObject.html

Instead of focusing solely on syntax mapping, from an engineering standpoint, it may be beneficial to organize levels within a map of Levels like this:

HashMap<String, Level> myLevels = new HashMap<String, Level>();

Answer №2

One suggestion from the commenters is to utilize a Map in Java to create an object with different types of values. These values could range from Strings to arrays of objects or even nested Maps.

The drawback, however, is that you would need to use a Map<String, Object>, leading to cumbersome instanceof checks every time you interact with it.

An alternative approach is to leverage a JSON binding library like Jackson. By defining a class such as Levels and annotating its variables, Jackson can handle the conversion of instances to JSON and vice versa. This method requires knowledge of your class structure. Jackson also offers a mode using untyped maps.

Another option is to conceptualize Levels as a tree structure and implement the Composite pattern. This involves creating an abstract class like Node holding a name, with concrete subclasses including IntegerNode, StringNode, DoubleNode, MapNode, and ArrayNode.

Answer №3

Utilize this modified JSON structure to generate the corresponding classes by utilizing jsonschema2pojo:

{
  "Levels":{
    "shapes":[
    {
      "bodytype" : "dynamic",
      "h" : "50.0000",
      "nameid" : "hofN7-1",
      "props" : {
          "id" : "properties"
      },
      "rotation" : "0.0000",
      "type" : "square",
      "uid" : "Av2EZQh",
      "w" : "50.0000",
      "x" : "20.0000",
      "y" : "20.0000"
    },
    {
      "bodytype" : "dynamic",
      "h" : "50.0000",
      "nameid" : "hofN7-2",
      "props" : {
        "gravMassScale" : "2",
        "id" : "properties",
        "inertia" : "2",
        "isBullet" : "true",
        "torque" : "2",
        "velocity" : {
          "x" : "2",
          "y" : "2"
        }
      }
    }]
  }
}

Verify the conversion of the JSON and customize additional options according to your requirements. Feel free to download and incorporate the generated classes in your Java project.

Hopefully, this information proves beneficial for you. Cheers!

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

Retrieve the maximum number of slots from a JSON file and implement them into the

I've encountered an issue with my upload form. After uploading and previewing an image, I want to add it to a list as long as the list still has available slots. Here's an example: If the maximum number of slots is set to 5, then you can add up ...

Trouble with Activating Bootstrap Popover with Initial Click Following Concealment

Could you please review this Demo and explain why the popover is not displaying on the first click after being hidden by the .data-date click event? var appcontent = '<button class="btn btn-primary data-date">Close Popover</button>'; ...

perform the directive function following the ng-cloak execution

I am having an issue with my content using the ng-cloak directive, as I would like to retrieve the height of an element using innerHeight() within a directive. However, when I use innerHeight(), the element is hidden by ng-cloak so the result is always 0. ...

restart the ongoing background task upon receiving a notification on an Android device

In my application, there are several activities. I am looking for a way to make the notification resume from the activity that is currently running in the background when it is clicked on. Right now, I have implemented the following code, but it always ta ...

Linked selection options for state, city, and postal code

I have set up a cascading dropdown list - State -> City -> Pincode . Instead of fetching data from the database, I am using JSON. The dropdown functions smoothly on the local server, but experiences slowness on the web server. Here is a snippet of ...

Unraveling the Depths: A Guide to Parsing Nested JSON Arrays of

Initially, I am aware that there have been similar inquiries raised before. Out of all the queries, I stumbled upon one that provided some assistance: , although I am encountering difficulties while trying to implement the suggested solution in my own situ ...

Ensure that the initial screen is updated automatically, even when it is defined with android:launchMode="singleTask"

I am currently dealing with 2 activities: Activity A and Activity B. These two activities call each other through intent - with Activity A calling Activity B. Activity B accesses the database and sends its data back to Activity A using putExtra() and getEx ...

Does adding .catch resolve a promise?

Being new to typescript / javascript, I have limited knowledge about promises. My current scenario involves creating three distinct promises within a cloud-function and subsequently returning them using Promise.all([promise1, promise2, promise3]). Each of ...

Router Express, parsing the body, and submitting a POST request

I have been experimenting with express.Router to organize my routes and testing post requests using Postman. I noticed that when I make a post request to /test without using router body-parser, everything works fine and I can view the body content. However ...

Trouble generating document with Firebase setDoc()

In my current project, I am successfully creating a new user with authentication and then using the generated UID to create a new document. Here is the code snippet: const currentUser = await auth.createUserWithEmailAndPassword(email, pass); consol ...

Creating a technique that can effectively handle multiple types of objects

Two sets of users, with similar attributes: HashSet<BuyerUser> HashSet<SellerUser> I need a method to serialize these objects as JSON and send them to a web API. However, I'm struggling to create a generic method that avoids code duplicat ...

Opting for classes over IDs

Within the parent class, there are two divs. One is located using $(this).parent('div').next('.deal-rolldown').show(); while the other $(this).parent('div').next('.client-rolldown').show(); does not seem to function ...

The inconsistency between updating data in the model and its corresponding binding in the controller

I've been attempting to implement this specific approach in my application, but I'm encountering difficulties. CountriesModel.js app.service('CountriesModel', ['$http', function($http) { $http.get(baseUrl + 'api/co ...

Using browserify "require" in console: A step-by-step guide

My Rails project now includes the browserify and pinyin packages, thanks to the browserify-rails installation. To find out more about the pinyin package, check out this link: https://github.com/hotoo/pinyin var pinyin = require("pinyin"); console.log(pin ...

When running from Silk Central, Silk test cannot initiate the push button

Having some trouble with closing an Internet Explorer windows security sign-in pop-up using a Silk4J script in a jar file. The script runs on a different machine via Silk Central's execution server, and works fine when the remote desktop session is ac ...

How to use JavaScript to identify the CSS property value of an HTML element

Everything seems fine until the alert pops up, but the 'if' statement is not executing properly. Here is the program stack. Is there a way to check the display property of a div to see if it's set to "block" or "none"? for(i=1;i<=10;i++ ...

Please explain the purpose and scope of a JavaScript document

let page = "temp"; function showPage() { alert(page); // temp or HTML Page } When I tried it, the result was "HTML Page", which makes sense. Is 'page' an object, reserved word, or a constant? If 'page' is an object, shouldn' ...

What is the process for initiating SQL Server?

Recently, I started learning SQL and for a school project, I created tables on a database called pizzeriaGennarino. I also developed a Java program to connect to the database. But now, I'm facing difficulties connecting to the MySQL server. UPDATE: ...

Combining multiple Float32Arrays to create a single Float32Array

I need help creating a function that can flatten multiple Float32Arrays into one large Float32Array const first = new Float32Array([1,2]); const second = new Float32Array([3,4,5]); const third = new Float32Array([6,7,8,9]); const chunks = [ ...

VueJS ensures that instance properties are reactive

Currently, I am in the process of developing a VueJS plugin that utilizes instance properties. I find myself needing to reintroduce some reactive values back into VueJS. After conducting my research: I have been struggling to grasp the concept behind Obj ...