Parsing JSON sub items in Android application using Java

Here is a snippet of my PHP file:

<?php
    $myObj = array(
        "name"=>"John" ,
        "age"=>"30" ,
        "post"=>[
            "title"=>"What is WordPress" ,
            "excerpt"=>"WordPress is a popular blogging platform" ,
            "description"=>"WordPress is a widely-used CMS by millions of bloggers",
            "meta"=>[
                "timing"=>["time"=>"3pm", "date"=>"3Jan"]
             ]
         ]
    );
    $obj = json_encode($myObj);
    echo $obj;
?>

When executed, the output looks like this:

{"name":"John","age":"30","post":{"title":"What is WordPress","excerpt":"WordPress is a blogging cms","description":"WordPress is an blogging cms used by million of bloggers","meta":{"time":"3pm","date":"3Jan"}}}

I have utilized HttpUrlConnection to fetch the JSON data. When I request for the title, excerpt, and description, everything works as expected.

However, I am facing difficulty retrieving the value of "time" under meta->timing.

Please assist me in understanding how to access this specific information. I am unsure if it is achievable or not.

Including Java code doesn't seem crucial at the moment, so I omitted it.

Answer №1

If you are utilizing the default JSONObject from the android API, extracting time from a raw json string is simple.

You can achieve this by creating a method like the one below:

public String getTime(String json){
    JSONObject obj = new JSONObject(jsonString);
    JSONObject post=  obj.getJSONObject("post");
    JSONObject meta = post.getJSONObject("meta");
    String time = meta.getString("time");
    return time;
}

Answer №2

If you're working with PHP code, it would be advisable to adapt your approach in the following manner:

function retrieveTime($jsonInput){
    $data = json_decode($jsonInput);
    $post = $data->post;
    $meta = $post->meta;
    $timing = $post->timing;
    $time = $timing->time;
    return $time;
}

Answer №3

Snippet for extracting time information from JSON

public String extractTimeInfo(String json){
    try {
        JSONObject obj = new JSONObject(json);
        JSONObject post = obj.getJSONObject("post");
        JSONObject meta = post.getJSONObject("meta");
        return meta.getString("time");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return "error retrieving time info";
}

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

Divide the string using brackets as delimiters

I'm having trouble splitting a string by brackets and getting extra empty values in my array. I attempted to use the solution from a similar question that was previously answered, but it splits the string while also introducing empty values. // faq ...

What is the best way to utilize an array that has been generated using a function?

After creating a customized function that generates an array of numbers, I encountered an issue where the array is not accessible outside the function itself. function customArrayGenerator (length, order){ // length = array length; order = integer order o ...

Extract the year from a string formatted as 1880-01-01T00:00:00.000

Looking to extract the year from an array of dates with format 1880-01-01T00:00:00.000. What's the most efficient method to accomplish this using JavaScript? ...

Initiate an Ajax request solely for the elements currently visible on the screen

I am currently facing an issue that requires a solution. Within our template, there are multiple divs generated with the same classes. Each div contains a hidden input field with the ID of the linked target site. My task is to utilize this ID to make aja ...

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...

Instructions for converting a JSON string into the proper format for a POST request in Swift

After using significant string interpolation, I have generated this JSON structure: { "headers":{ "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="11747c70787d517469707c617d743f7e6376">[email protect ...

Error: The gulp-cssmin plugin encountered a TypeError because it attempted to read the property '0' of a null

I am attempting to condense my code, but I am encountering this error: D:\gulp-compiler\node_modules\gulp-cssmin\node_modules\clean-css\lib\selectors\extractor.js:66 return name.replace(/^\-\w+\-/, ...

What causes the `d-none` class to toggle on and off repeatedly when the distance between two div elements is less than 10 during window resizing?

My primary objective is to display or hide the icon based on the width of the right container and the rightButtonGroupWrapper. If the difference between these widths falls below 10, the icons should be shown, otherwise hidden. However, I'm facing an i ...

Is the Okta SDK compatible with all identity providers?

I am looking to incorporate a wide range of Identity providers into my app, such as Auth0 SSO OIDC, Onelogin SSO OIDC, Google SSO OIDC, and others. Is it possible to use this solution to make that happen? https://github.com/okta/okta-auth-js ...

tips on setting the time format in dimple.js

Trying to create a multi-line graph using dimple.js based on some sample code. I have flattened my JSON into an array and thought I had the code down, but I'm stuck. I am including these 2 libraries (using cloudflare dimple for security reasons): &l ...

Best practices for sending an object from client to server using Node.js

What is the best way to transfer a large object from client side to my node.js server? The object is currently stored in a variable within my script tags. ...

How to use jQuery to dynamically add a variable to a request in Laravel 5.2

Is it feasible to append a variable to the Laravel cookie in the client using jQuery? Understandably, the Cookie is linked to the request during GET? Can you include a variable in the $request container in Laravel 5.2 using jQuery before initiating a GET ...

CRUD operations are essential in web development, but I am encountering difficulty when trying to insert data using Express

I am currently attempting to add a new category into the database by following the guidelines provided in a course I'm taking. However, I am encountering difficulties as the create method does not seem to work as expected. When I try it out in Postman ...

Issue - Following error occurred in the file connection.js located in node_modules/mysql2 library: Module not found: Unable to locate 'tls' module

I've encountered an error in our Next JS applications where tls is not found. I have tried several troubleshooting steps including: 1. Updating Node modules 2. Using both mysql and mysql2 3. Running npm cache clean --force 4. Removing node_modules di ...

Execute the function when the element comes into view

Is there a way to create a function that will automatically attach itself to an element when it comes into view? I have multiple elements on my page - element1, element2, and element3. Instead of using a large if statement, I would like to write a functio ...

The transmission of information via Java, Ajax, and json through web services is currently experiencing issues

Seeking assistance with a persistent error in my code. It keeps returning an error, but no error message is displayed, only the console.log. Any suggestions on how to debug this issue or if you could identify what's wrong? Thanks! Sami function fo ...

Modifying a JavaScript code with document.write(variable)

I am working with a Javascript function function setComparison(data) { var w= window.open('', 'comparison', 'width=600, height=400'); w.document.open(); w.document.write(getComparisonContent(data)); w.document ...

Measuring data entries within JSON array utilizing JavaScript and Postman

A specific component is returning two records: { "value": [ { "ID": 5, "Pupil": 1900031265, "Offer": false, }, { "ID": 8, "Pupil": 1900035302, "Offer": false, "OfferDetail": "" } ] } My task i ...

How can you stop a document event listener from triggering?

Utilizing document.addEventListener('touchstart', this.onDocument); allows me to recognize when a user taps outside of an element. However, within my button click handler, the following code is present: toggleItemActive(e) { e.stopPropa ...

These specific resources don't have a cache expiration set. Wondering how to properly set a cache expiration for a JavaScript file

I am working on a web application that utilizes external JavaScript files. Upon running Google's page speed tool, I realized that several resources are missing cache expiration settings, including images and CSS files. Can you provide examples of how ...