Noufal
Noufal

Reputation: 447

How to parse JSON array with single element without any object in Retrofit?

I am using Retrofit which uses GSON for parsing.The server will check the parameter i am sending and returns two responses Accordingly. If the parameter is valid i am getting the following response

[
  true
]

If it is not valid then i get response as,

   [
      "Sorry, <em class=\"placeholder\">[email protected]</em> is not recognized as a user name or an e-mail address."
    ]

This is the call method i am using.

@Override

public void onResponse(Call<String> call, Response<String> response) {
mProgressBar.setVisibility(View.GONE);
    Log.d("Response ", ""+response);


}

here response.body giving me as null. But there is a response.which is viewable in OKHttp Log.

Upvotes: 1

Views: 1283

Answers (4)

Hala.M
Hala.M

Reputation: 766

since the server return diffrent codes

can you try

Call<Void> 

and check the response code this might work for now until you know what is wrong void will not parse any thing so it shouldn't cause a crash

///////

did you try

Call<ArrayList<String>>

also are you sure the server returns 200 in both cases ?

Upvotes: 0

h_patel
h_patel

Reputation: 744

you can try this

 JSONArray jArray=new JSONArray(yourString);

 String str=jArray.getString(0);;
 if(str.equalsIgnoreCase("true")
 {
      //your code
 }else
 {
 }

Upvotes: 1

Ilya Gazman
Ilya Gazman

Reputation: 32221

You can use JsonParser provided by Gson. It will parse the json input to dynamic JsonElement.

Look at MByD example:

 public String parse(String jsonLine) {
    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject  jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("data");
    JsonArray jarray = jobject.getAsJsonArray("translations");
    jobject = jarray.get(0).getAsJsonObject();
    String result = jobject.get("translatedText").toString();
    return result;
}

Upvotes: 0

Hardik Vaghasiya
Hardik Vaghasiya

Reputation: 298

JSONArray jarray = new JSONObject(jsonString);
for (int i = 0; i < jarray.length(); i++) {
      String string = jarray.getString(i);
      log.e("String",string);
}

that's working great. Please try this.

Upvotes: 0

Related Questions