Developing an android application that handles a specific format of JSON data

I have received a JSON in the following format:

var list=[{"Name":"arun","City":"xyx","CountryName":"KUWAIT"},"Name":"Amal","City":"abb","CountryName":"BAHRAIN"}];

This JSON is sent from my web server to my Android app as a String value. I need to convert it into the proper JSON format. The size of the string may vary depending on certain conditions. So far, I have only dealt with and converted JSON strings and arrays that were received in this format:

{"Android":[{"slno":"1","name":"abc","number1":"123","number2":"456"},{"slno":"2","name":"def","number1":"789","number2":"000"},{"slno":"3","name":"","number1":"234","number2":"567"},{"slno":"4","name":"ghi","number1":"890","number2":"345"}]}

However, I am unsure how to convert the initial JSON string received in my Android app. Can someone please assist me in converting it properly? How can I go about achieving this conversion within my app?

Answer №1

I'm not sure what you mean by conversion. I assume you are looking to extract data from the given JSON format:

[ // Array of JSON objects
    {  // First JSON object
        "Name": "arun",
        "City": "xyx",
        "CountryName": "KUWAIT"
    },
    {  // Second JSON object
        "Name": "Amal",
        "City": "abb",
        "CountryName": "BAHRAIN"
    }
]

To extract the data, you can use the following code:

JSONArray jsonArray = new JSONArray("jsonString");
for(int index = 0; index < jsonArray.length(); index++)
{
     JSONObject jsonObject = (JSONObject) jsonArray.getJSONObject(index);
     String name = jsonObject.getString("Name");
     String city = jsonObject.getString("City");
     String country = jsonObject.getString("CountryName"); 
}

Answer №2

When making an HTTP request, use the following code snippet (replace url with your actual URL):

HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 500);

Client = new DefaultHttpClient(params);
httpget = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
mContent = Client.execute(httpget, responseHandler);

To retrieve data from the response:

JSONObject jsonObject = new JSONObject(mContent);
String firstname = jsonObject.getString("firstName");
String id = jsonObject.getString("Name"");
String headline = jsonObject.getString("City");
String lastName = jsonObject.getString("CountryName");

Then, implement this code inside an asynctask:


FINAL CODE::

public class AsyncTaskActivity extends Activity implements OnClickListener {

        Button btn;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            btn = (Button) findViewById(R.id.button1);
            // because we implement OnClickListener we only have to pass "this"
            // (much easier)
            btn.setOnClickListener(this);
        }

        public void onClick(View view) {
            // detect the view that was "clicked"
            switch (view.getId()) {
            case R.id.button1:
                new LongOperation().execute("");
                break;
            }
        }

        private class LongOperation extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {

                HttpParams params = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(params, 500);

               Client = new DefaultHttpClient(params);
               httpget = new HttpGet(url);
               ResponseHandler<String> responseHandler = new BasicResponseHandler();
               mContent = Client.execute(httpget, responseHandler);


              JSONObject jsonObject = new JSONObject(mContent);
              String firstname = jsonObject.getString("firstName");
              String id = jsonObject.getString("Name"");
              String headline = jsonObject.getString("City");
               String lastName = jsonObject.getString("CountryName");


                return "Executed";
            }

            @Override
            protected void onPostExecute(String result) {
                TextView txt = (TextView) findViewById(R.id.output);
                txt.setText("Executed"); 
            }

            @Override
            protected void onPreExecute() {}

            @Override
            protected void onProgressUpdate(Void... values) {}
        }
    }

If you encounter any debugging issues, feel free to let me know

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

Utilizing SEO and incorporating special characters like !# in a website's URL

I came across an interesting concept about designing a website that utilizes AJAX to load each page section without compromising SEO. It involved incorporating !# in the URL, similar to the approach adopted by Twitter. However, I've been unable to loc ...

How can I reverse a regex replace for sentences starting with a tab in JavaScript?

In order to format the text properly, I need to ensure that all sentences begin with only one Tab [key \t] and remove any additional tabs. input This is aciton Two tab One tabdialog This is aciton Two tab Second tabdialog out ...

Is it recommended to update my peer dependencies when upgrading my RN version?

Recently, I took on the task of updating my old project from RN 0.61.x to 0.70.x and react 16 to react 18. During this process, I encountered a challenge with dependencies that were tied to older versions of React Native in their peer dependencies. This is ...

Creating a hierarchical JSON structure using a database query in JavaScript

Currently, I am in the process of building a nested JSON object by parsing a query string obtained from an SQL database. This constructed JSON object will then be utilized by Angular to display data in the user interface using angular2-query-builder. The ...

Is it possible to adjust the element's position using the code "element.style.top = window.scrollY"?

Recently, I attempted to create a floating input element that would follow the scroll. After much effort, I managed to achieve it and the code is provided below. However, I encountered an issue when trying to change "setText(window.scrollY)" to ...

Avoid constantly updating the rendering in React by utilizing callback functions

Is there a way to prevent Component B from rendering when I am only making changes in Component A? For example, if console.log("A") is associated with Component A and console.log("B") with Component B, I expect that updating text in Component A will only ...

Getting a random value within a Struts set tag can be achieved by utilizing the <

Using struts2 tags in my application, I am trying to dynamically change the value in a JavaScript array using s:set tags. However, when I add the values dynamically, the output I get is 2012 - diff + 1, whereas I am expecting 2011. How can I achieve this? ...

Utilizing AngularJS to access the corresponding controller from a directive

When I have HTML structured like this... <div ng-app="myApp"> <div ng-controller="inControl"> I enjoy sipping on {{beverage}}<br> <input my-dir ng-model="beverage"></input> </div> </div> a ...

Collection of clickable images that lead to creatively designed individual pages

Being relatively new to JavaScript and jQuery, my knowledge is solid when it comes to HTML & CSS. Currently, I have a page with 20 minimized pictures (with plans to increase to 500+ images) that open into a new page when clicked. Although I have no issues ...

Get the docx file as a blob

When sending a docx file from the backend using Express, the code looks like this: module.exports = (req, res) => { res.status(200).sendFile(__dirname+"/output.docx") } To download and save the file as a blob in Angular, the following code snippet i ...

Access the file using NodeJS and SailsJS for download

I am working on creating an API to enable the download of a static file named test.js. Upon testing the API using Postman, I noticed that instead of initiating a download process, it simply displays the content of the file. Is this behavior acceptable? a ...

Modify the chosen value of a dropdown list that is created dynamically

In the JSP page, there is a dynamic drop-down list generated as shown below: <table BORDER=4 BORDERCOLOR=ORANGE width="300px"> <tr> <td>Model:</td> <td><select name="model" id="model"> &l ...

Click on the div to automatically insert its text into the textarea

I am looking for a way to enable users to edit their posts easily. My idea is to have them click on a link, which will then hide the original div containing their post and reveal a new div with the old text inside a textarea for editing. Despite searching ...

Tips for preserving scroll location on Angular components (not the window) when navigating

My current layout setup is like this: https://i.sstatic.net/hOTbe.png In essence <navbar/> <router-outlet/> The issue I'm facing is that the router-outlet has overflow: scroll, making it scrollable (just the outlet section, not the ent ...

Using THREE.js to incorporate a stroke above extruded text

Looking to enhance text with a horizontal line above it: var geo = new THREE.TextGeometry("x", geometry_options); var mat = new THREE.MeshBasicMaterial({color: 0, side:THREE.DoubleSide}); geo.computeBoundingBox (); var vec = new THREE.Shape(); vec.moveTo( ...

Disabling exit view mode in the Unlayer email editor: A guide

Currently, I am able to open a preview using the code unlayer.showPreview("desktop"). However, whenever the user clicks on the overlay, they are exiting the preview mode. Is there a way to prevent the user from closing the preview? Unfortunatel ...

Can a multipart POST request contain nested MultipartEntities or FormBodyParts?

Currently, I am attempting to construct a server POST request utilizing MultipartEntity with the following parameters: {"parameter1"=>"parameter1", "parameter2"=>{"sub_parameter1"=>"sub_parameter1", "sub_parameter2"=>"sub_parameter2"}} My cur ...

Error: Simple controller causing double rendering issue

I encountered an unusual error while working on my API Rails application: AbstractController::DoubleRenderError in Api::V1::AdsController#restaurant Multiple render and/or redirect calls were made in this action. It is important to note that only one rend ...

Creating arrays in JavaScript with or without the use of jQuery

In my JavaScript script, I am defining this array: var status=[ { "name":"name1", "level":0 }, { "name":"name2", "level":0 }, { "name":"name3", "level":0 }, { "name":" ...

What methods can I use to streamline integration with minimal lines of code?

Seeking help with JavaScript: Recently dived into JavaScript and managed to create the desired functionality for my navigation menu. However, I suspect that my code is not optimized as I find myself repeating lines unnecessarily. Here's a snippet of ...