Emmett Miller
Emmett Miller

Reputation: 33

Parsing extremely simple JSON from a URL in in Android

I have tried everything online to try to parse this JSON but nothing seems to work. Here is the JSON:

{"salonphoebe":true,"salonvo":false}

That's it. It is only booleans. It is from an HTTP website if that is important at all. How do I do parse this extremely simple JSON from http://example.com in Java in Android Studio? I am trying to create Booleans based on these in my app. I know this question is on this website a lot but I have literally tried 10 solutions but nothing will work. Thank you.

Upvotes: 0

Views: 102

Answers (2)

Emmett Miller
Emmett Miller

Reputation: 33

Okay I have solved my own problem. Here is everything I learned and what I did. I want to help anyone else with this problem if they come across this issue. First I added this to my androidmanifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Then I added this between the tags in the androidmanifest.xml beucase the link I am parsing the JSON from is an HTTP link:

android:usesCleartextTraffic="true"

Really quickly import all of this into your mainactiviy.java:

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

Then we get into the hard stuff. There are two parts to parsing JSON data from the internet. First, you must read the JSON (meaning put the JSON from online into a String) from the URL and then you must organize the String of JSON into separate variables. So let's start on the HTTP Request. I created an Async class in my MainActivity.java (under the OnCreate) that I found online that looks like this:

public class HttpGetRequest extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        try {
            String url = "http://example.com/example.php";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            System.out.println("Test");
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }

            in.close();

            String jsonResponse = response.toString();
            return  jsonResponse;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            JSONObject json = new JSONObject(result);
            boolean myJsonBool = json.optBoolean("samplestringinyourjson");
            if(hasPaid){
                //do something 
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
}

Okay so basically the reason we put this in an Async class is because java won't let you make an HTTP Request in your OnCreate. What the doInBackground is doing is fetching the JSON data and putting it into the string like I said. The OnPostExecute is separating that string into boolean values and doing stuff with it. Lastly, paste this into your OnCreate or it won't work:

new HttpGetRequest().execute();

That's it. If you have questions ask and hopefully I can see it.

Upvotes: 0

Ruchira Randana
Ruchira Randana

Reputation: 4179

Try the following code.

try {
  JSONObject json = new JSONObject(your - json - string - here);
  boolean b1 = json.optBoolean("salonphoebe");
  boolean b2 = json.optBoolean("salonvo");
 } catch (JSONException e) {
  e.printStackTrace();
 }

Upvotes: 1

Related Questions