-2

I have a JSON file that contains two objects. This file is in server side.

[ {"param1":"market"}, {"param2":"you"} ]

I want to parse these objects and set to my String param1,param2

private String param1 = null;
private String param2 = null;

I can not understand how to code. Please give me sample code for this.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
jancooth
  • 555
  • 1
  • 10
  • 25
  • @Dalton I did not know how to parse. The link you wrote who asked that question said " I have already got JSON string by code " – jancooth Dec 11 '17 at 18:30

3 Answers3

0
[ {"param1":"market"}, {"param2":"you"} ]

The square brackets are showing that your response starts with JSON array. So, you should have key name of JSON array so that you can find the value of JSON objects from JSON array.

Anchal Singh
  • 329
  • 3
  • 13
0

so you need to call the server to get the jsonString you can make service call like this by passing url and getting the json str

public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

then you use the jsonStr you get from the call like this.

String jsonStr = makeServiceCall(String reqUrl);
JSONArray jsonArr= new JSONArray(jsonStr);
JSONObject jsonObjectOne = jsonArr.getJSONObject(0);
String param1 = jsonObjectOne.getString("param1");
JSONObject jsonObjectTwo = jsonArr.getJSONObject(1);
String param2 = jsonObjectTwo.getString("param2");
Mark Samy
  • 148
  • 10
0
String string = "[ {"param1":"market"}, {"param2":"you"} ]"

JSONArray arr = new JSONArray(string);

JSONObject firstPart = arr.getJSONObject(0);

JSONObject secondPart = arr.getJSONObject(1);

firstPart.getString("param1");
secondPart.getString("param2");
Soon Santos
  • 2,107
  • 22
  • 43
  • my objects are in server side. I keep it in txt file. Can you modify your code ? – jancooth Dec 11 '17 at 19:41
  • This code seems to be a string or already an JSONArray, if it is the first, do it like the code I wrote. If it is the second case you just delete the first two lines. – Soon Santos Dec 11 '17 at 19:45