I am building an android application and I am new to json. I am fetching below josn formate -
{
"contact"[
{
"key1": "hey1",
"key2": [
{
"key3": "hey2"
}
]
}
]
}
I am using below code to fetch key1 value. Now problem I am facing is how to fetch key3 value -
jsonString = http.makeServiceCall(url, ServiceHandler.GET, null);
if (jsonString != null) {
try {
JSONObject jsonObj = new JSONObject(jsonString);
// Getting JSON Array node
questions = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < questions.length(); i++) {
temp_obj = questions.getJSONObject(i);
key1Array.add(temp_obj.getString("key1").toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Please help me
If you want to use Gson to parse your json data. Let try it:
First of all, you must modify your json like this:
{
"contact":[
{
"key1": "hey1",
"key2": [
{
"key3": "hey2"
}
]
}
]
}
Second add Gson to your libs and sync build.gradle: download here extract it, and copy/past gson-2.2.4.gson to libs folder.
Third Create some class:
FullContents.java:
public class FullContents {
private List<ObjectKey> contact;
public List<ObjectKey> getContact() {
return contact;
}
public void setContact(List<ObjectKey> contact) {
this.contact = contact;
}
}
ObjectKey.java:
public class ObjectKey {
private String key1;
private List<ObjectKey3> key2;
public List<ObjectKey3> getKey2() {
return key2;
}
public void setKey2(List<ObjectKey3> key2) {
this.key2 = key2;
}
public String getKey1(){
return key1;
}
public void setKey1(String key1){
this.key1 = key1;
}
}
ObjectKey3.java:
public class ObjectKey3 {
private String key3;
public String getKey3(){
return key3;
}
public void setKey3(String key3){
this.key3 = key3;
}
}
And Finally, get data from url:
private class ParseByGson extends AsyncTask<String,Void,FullContents> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected FullContents doInBackground(String... params) {
FullContents fullContents = null;
try {
URL url=new URL(params[0]);
InputStreamReader reader=new InputStreamReader(url.openStream(),"UTF-8");
fullContents=new Gson().fromJson(reader,FullContents.class);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fullContents;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(FullContents results) {
super.onPostExecute(results);
ObjectKey objectKey = results.getContact().get(0);
Log.e(">>",objectKey.getKey1()+"--");
}
}
you can put below code to onCreate:
ParseByGson parseByGson = new ParseByGson();
parseByGson.execute(urlStringHere);
Update: Explain
1st of all: your json appears to be not valid (missing ':' after "content");
After reviewing thins:
You can use the named getters to retrieve many types of results (object, int, string, etc);
JSONObject contact = jsonObj.getJSONObject("contact"); // {"key1":"hey1","key2":[{"key3":"hey2"}]}
or
String key1 = jsonObj.getString("key1"); // hey1
To retrieve key3, you should use:
JSONObject contact = jsonObj.getJSONObject("contact");
JSONObject key2 = contact.getJSONObject("key2");
String key3 = key2.getString("key3");
Adapt the following code to what you are coding
for (int i = 0; i < questions.length(); i++) {
temp_obj = questions.getJSONObject(i);
key1Array.add(temp_obj.getString("key1"));
JSONObject temp_objKey2 = temp_obj.getJSONObject("key2");
Key2Object key2Object = new Key2Object();
key2Object.add(temp_objKey2.getString("key3"));
key1Array.add(key2Object);
}
Related
I want to fetch data from api through volley library.
I am retrieving a JSON Object And Json Arrray via the Volley class in Android .I know how to get request but I am really struggling to parse this giant nested json .
I want to get synonyms And antonyms From the list
I want to get data from Synonmys Array and antonyms array....... Here is the link to api . Link
or Image Of Json Api - enter image description here
My Main Activity
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
// creating a new json object and
// getting each object from our json array.
try {
// we are getting each json object.
JSONObject responseObj = response.getJSONObject(i);
String word = responseObj.getString("word");
String phonetic = responseObj.getString("phonetic");
JSONArray jsonArray = responseObj.getJSONArray("meaning");
for (int k = 0; k < response.length(); k++) {
?? what to do here ????????
------------------------need help here-------------------------------
}
synonymsList.add(new synonymsModel(word,phonetic, synonyms,antonyms));
buildRecyclerView();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
queue.add(jsonArrayRequest);
}
Model class
public class synonymsModel {
String word, phonetic , antonyms, synonyms;
public synonymsModel(String word, String phonetic, String antonyms, String synonyms) {
this.word = word;
this.phonetic = phonetic;
this.antonyms = antonyms;
this.synonyms = synonyms;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public String getAntonyms() {
return antonyms;
}
public void setAntonyms(String antonyms) {
this.antonyms = antonyms;
}
public String getSynonyms() {
return synonyms;
}
public void setSynonyms(String synonyms) {
this.synonyms = synonyms;
}
}
I am coding a Discord Giveaway Bot with Java. I am saving all the details of the Giveaway to a JSON file. Now I want to read the entries list and if the Users ID is not in the list I want to add it and save the file.
Here is the Giveaway Class:
public class Giveaway {
private String prize;
private long time;
private Integer winners;
private List<String> entries;
public Giveaway(String prize, Integer winners, long time, List<String> entries) {
this.prize = prize;
this.winners = winners;
this.time = time;
this.entries = entries;
}
public Giveaway() {}
public String getPrize() {
return prize;
}
public void setPrize(String prize) {
this.prize = prize;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public Integer getWinners() {
return winners;
}
public void setWinners(Integer winners) {
this.winners = winners;
}
public List<String> getEntries() {
return entries;
}
public void setEntries(List<String> entries) {
this.entries = entries;
}
}
When the GW is created the JSON looks like this:
{
"prize": "Discord Nitro",
"time": 1641732935,
"winners": 2,
"entries": []
}
Then when the user clicks a button it should read the list look if the ID is in the list and if not add the id. But when I save the list the whole JSON file changes.
How I read it out and save it:
public class ButtonClick extends ListenerAdapter {
private static Reader reader;
private static Giveaway giveaway = new Giveaway();
public void onButtonClick(ButtonClickEvent event) {
event.deferEdit().queue();
try {
reader = Files.newBufferedReader(Path.of(GiveawayStats.getGiveawayStats().getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
}
if (event.getButton().getId().equals("gwEnter")) {
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(reader).getAsJsonObject();
JsonArray jsonEntries = obj.get("entries").getAsJsonArray();
long time = obj.get("time").getAsLong();
List<String> entries = new ArrayList<>();
for (JsonElement entrie : jsonEntries) {
entries.add(entrie.toString());
}
if (entries.contains(event.getMember().getId())) {
event.getChannel().sendMessage("Already in!").queue();
} else {
entries.add(event.getUser().getId().strip());
printToJson(entries);
}
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void printToJson(List<String> entries) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setVersion(2.0);
Gson gson = gsonBuilder.setPrettyPrinting().create();
giveaway.setEntries(entries);
try (Writer writer = new FileWriter(GiveawayStats.getGiveawayStats().getPath())) {
gson.toJson(giveaway, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
After the print so JSON the file looks like this:
{
"time": 0,
"entries": [
"695629580014321747"
]
}
And when I click the Button again it looks like this:
{
"time": 0,
"entries": [
"\"695629580014321747\"",
"695629580014321747"
]
}
So why is my IF condition not working?
You are using entrie.toString() which gives you the string that is used for console output. You should be using entrie.getAsString() instead.
Furthermore, you are also using a lot of deprecated things with JsonParser which should be replaced. new JsonParser().parse(...) should be replaced by JsonParser.parseReader(...).
Above all that, it is highly recommended using a database for this kind of task. Something such as SQLite or Redis would be much better at handling concurrent changes and redundancy. Or at least, you should use a try-with-resources for your reader.
try (Reader reader = ...) {
JsonElement json = JsonParser.parseReader(reader).getAsJsonObject();
...
}
I want to parse json from json object and put it on textview. I tried some method but failed. The error:
expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
API SERVICE: Full ver http://139.255.86.189:83/service/api/checklistpertanyaan/1
{
"success": true,
"data": [
{
"idRchecklistpompa": "1",
"nmChecklist": "Membersihkan Body Pompa"
},
{
"idRchecklistpompa": "2",
"nmChecklist": "Membersihkan Kabel Tray Pompa"
},
Harian.java
public class Harian {
#SerializedName("idRchecklistpompa")
#Expose
private String idRchecklistpompa;
#SerializedName("nmChecklist")
#Expose
private String nmChecklist;
public String getIdRchecklistpompa() {
return idRchecklistpompa;
}
public String getNmChecklist() {
return nmChecklist;
}
public void setIdRchecklistpompa(String idRchecklistpompa) {
this.idRchecklistpompa = idRchecklistpompa;
}
public void setNmChecklist(String nmChecklist) {
this.nmChecklist = nmChecklist;
}
}
MainActivity.java
public class HarianActivity extends AppCompatActivity {
private TextView textViewResult;
/*private static String url = "http://139.255.86.189:83/service/api/checklistpertanyaan/1";*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_harian);
textViewResult = findViewById(R.id.text_view_result);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://139.255.86.189:83/service/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
HarianApi harianApi = retrofit.create(HarianApi.class);
Call<List<Harian>> call = harianApi.getHarian();
call.enqueue(new Callback<List<Harian>>() {
#Override
public void onResponse(Call<List<Harian>> call, Response<List<Harian>> response) {
if (!response.isSuccessful()) {
textViewResult.setText("CodeL " + response.code());
return;
}
List<Harian> harians = response.body();
for (Harian harian : harians) {
String content = "";
content += "ID " + harian.getIdRchecklistpompa() + "\n";
content += "NAMA " + harian.getNmChecklist() + "\n";
textViewResult.append(content);
}
}
#Override
public void onFailure(Call<List<Harian>> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
}
I would expect JSON that encapsulated a List of Harians to look like this:
[
{
"idRchecklistpompa": "1",
"nmChecklist": "Membersihkan Body Pompa"
},
{
"idRchecklistpompa": "2",
"nmChecklist": "Membersihkan Kabel Tray Pompa"
}
]
Instead, yours begins with:
{
"success": true,
"data": [
...
So it isn't correct for your API to return List<Harian>. Instead, your API should return a different class which looks more like:
public class Container {
#SerializedName("success")
private boolean success;
#SerializedName("data")
List<Harian> data;
public static class Harian {
#SerializedName("idRchecklistpompa")
#Expose
private String idRchecklistpompa;
#SerializedName("nmChecklist")
#Expose
private String nmChecklist;
public String getIdRchecklistpompa() {
return idRchecklistpompa;
}
public String getNmChecklist() {
return nmChecklist;
}
public void setIdRchecklistpompa(String idRchecklistpompa) {
this.idRchecklistpompa = idRchecklistpompa;
}
public void setNmChecklist(String nmChecklist) {
this.nmChecklist = nmChecklist;
}
}
}
And have your Retrofit API return Container rather than List<Harian>
Not sure if I understand but, to debug the problem what I would do is:
1.- Check as a String that response is a well formed JSON String.
Log.d(TAG, "My JSON String: " + response.code());
1.5.- Check if that string is a JSONObject or a JSONArray
2.- Probably try to create a JSONObject/JSONArray from that String to see if it triggers an exception.
try {
JSONObject jsonObject = new JSONObject(response.code());
} catch (JSONException e) {
e.printStackTrace();
}
3.- Try to parse the JSONObject but checking for exceptions:
try {
String nmChecklist = jsonObject.getString("nmChecklist");
} catch (JSONException e) {
e.printStackTrace();
}
4.- If you want to avoid exceptions since some objects may or may not have a key or value:
String nmChecklist = jsonObject.has("nmChecklist") && !jsonObject.isNull("nmChecklist") ? jsonObject.getString("nmChecklist") : null;
I hope this helps.
I think there is some problem with your class. The response is different from your pojo class. See json to pojo and create your Model as per the generated pojo.
{ "StatusCode": 200, "StatusDescription": "OK", "ErrorMessage":
"", "ErrorDetail": "", "Results": [
{
"Key": "AccessTokens",
"Value": "[{\"Key\":\"XXXXX",
\"Value\":\"BABABA\"},{\"Key\":\"DIDADIDA\",\"Value\":\"YYYYY"
} ]"}]}
This is the response i will get when i success call the API. The datatype of "Results" is List. Can anyone explain for me how to get the "Key" and the "Value".
My Object Classes
public class KeyValueItem {
private String Key;
private String Value;
public String getKey() {
return Key;
}
public void setKey(String key) {
Key = key;
}
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
}
}
Response Class
public class RestServiceResponse {
#SerializedName("StatusCode")
#Expose
public int StatusCode;
public int getStatusCode() {
return StatusCode;
}
#SerializedName("StatusDescription")
#Expose
public String StatusDescription;
public String getStatusDescription() {
return StatusDescription;
}
#SerializedName("ErrorMessage")
#Expose
public String ErrorMessage;
public String getErrorMessage() {
return ErrorMessage;
}
#SerializedName("ErrorDetail")
#Expose
public String ErrorDetail;
public String getErrorDetail() {
return ErrorDetail;
}
#SerializedName("Results")
#Expose
public List<KeyValueItem> Results;
public List<KeyValueItem> getResults() {
return Results;
}
}
Anyone help please =(
Some of my code:
public void onResponse(Call<RestServiceResponse> call, Response<RestServiceResponse> response) {
Log.i("ddsddsadsa", String.valueOf(response.code()));
RestServiceResponse restServiceResponse = response.body();
if(restServiceResponse.getStatusCode() == 200){
List<KeyValueItem> list = response.body().getResults();
JSONArray jsonArray = new JSONArray(list);
try {
JSONObject job = jsonArray.getJSONObject(1);
String testttt = job.getString("Key");
Log.i("dsadsadsadas", testttt);
} catch (JSONException e) {
e.printStackTrace();
}
}
2 things you have to understand first.
Your JSON data is not in valid format. It contains \ (slashes) to escape double quotes in key-value pair. To confirm whether the returned JSON data is valid or not please copy & paste your JSON response into JSON validator and Formatter. Maybe problem in server script.
If you're using GsonConvertorFactory with Retrofit, Retrofit will automatically converts JSON response data to POJO internally. So, you don't need parse it again inside onResponse() method. If you get proper JSON response from server side then use it like below.
public void onResponse(Call<RestServiceResponse> call, Response<RestServiceResponse> response) {
// code....
RestServiceResponse restServiceResponse = response.body();
if (restServiceResponse.getStatusCode() == 200) {
List<KeyValueItem> list = response.body().getResults();
for(int i = 0; i < list.size(); i++) {
KeyValueItem kvi = list.get(i);
// do whatever you want with kvi object
}
}
}
public void onResponse(Call<RestServiceResponse> call, Response<RestServiceResponse> response) {
Log.i("ddsddsadsa", String.valueOf(response.code()));
RestServiceResponse restServiceResponse = response.body();
if(restServiceResponse.getStatusCode() == 200){
List<KeyValueItem> list = response.body().getResults();
for(KeyValueItem keyValueItem : list) {
String key = keyValueItem.getKey();
String value = keyValueItem.getValue();
Log.i("Keykeykey", key);
}
try {
JSONArray jsonArray = new JSONArray(value);
for(int i = 0; i < jsonArray.length();i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String keykey = obj.getString("Key");
String VAlll = obj.getString("Value");
Log.i("c1111",keykey);
Log.i("c222222", VAlll);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}else if(restServiceResponse.getErrorMessage() != null){
builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("Error");
builder.setMessage(restServiceResponse.getErrorMessage());
builder.setPositiveButton("Ok",null);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
OK. Btw. i have try this to get my result. and it works!
To answer those about a invalid JSON format maybe because i have changed the value of the JSON so may have some mistake on it.
Below is the final log i get:
74/com.appandus.user.konnect I/Keykeykey: AccessTokens 07-12
17:14:38.177 6274-6274/com.appandus.user.konnect I/c1111: XXXXX 07-12
17:14:38.177 6274-6274/com.appandus.user.konnect I/c222222: BABABA
07-12 17:14:38.177 6274-6274/com.appandus.user.konnect I/c1111: NS/NH
: DIDAIDA 07-12 17:14:38.177 6274-6274/com.appandus.user.konnect
I/c222222: YYYYYY
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Using GSON to parse a JSON with dynamic "key" and "value" in android
(2 answers)
Closed 5 years ago.
This is my JsonResponse , and since its not in array i am facing some difficulties , can any one help me out ? in android
{
"errorno": "0",
"responsemsg": "Login Success.",
"busid": "1234",
"returnmobileno": "1234567890"
}
try this
try {
JSONObject lJsonObject = new JSONObject(response);
String errorno = lJsonObject .getString("errorno");
String responsemsg = lJsonObject .getString("responsemsg");
String busid = response.lJsonObject ("busid");
String returnmobileno = lJsonObject .getString("returnmobileno");
} catch (JSONException e) {
e.printStackTrace();
}
Try this,
try {
String errorno = response.getString("errorno");
String responsemsg = response.getString("responsemsg");
String busid = response.getString("busid");
String returnmobileno = response.getString("returnmobileno");
Log.d(TAG, "errorno:" + errorno+" responsemsg:"+responsemsg+" busid:"+busid+" returnmobileno:"+returnmobileno);
} catch (JSONException e) {
e.printStackTrace();
}
use below code to pass your strong
serverData = gson.fromJson(response, ServerData.class);
in build.gradle -> dependencies
// retrofit, gson
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
public class ApiClient {
public static final String SERVER_BASE_URL = "http://example.com/abc/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(SERVER_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public interface ApiInterface {
#POST("appServices/getData.php")
#FormUrlEncoded
Call<ResponseBody> getAllDataJSONFromServer(#Field("vcode") String vcode);
}
public class ServerData implements Parcelable {
public static final Creator<ServerData> CREATOR = new Creator<ServerData>() {
#Override
public ServerData createFromParcel(Parcel in) {
return new ServerData(in);
}
#Override
public ServerData[] newArray(int size) {
return new ServerData[size];
}
};
private static final int VERSION = 1;
#SerializedName("errorno")
private String errorno;
#SerializedName(responsemsg)
private String responsemsg;
#SerializedName("busid")
private String busid;
#SerializedName("returnmobileno")
private String returnmobileno;
private void readFromParcel(Parcel in) {
if (in.readInt() == VERSION) {
errorno = in.readString();
responsemsg = in.readString();
busid = in.readString();
returnmobileno = in.readString();
}
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(VERSION);
parcel.writeString(errorno);
parcel.writeString(responsemsg);
parcel.writeString(busid);
parcel.writeString(returnmobileno);
}
#Override
public int describeContents() {
return 0;
}
public String getErrorno() {
return errorno;
}
public void setErrorno(String errorno) {
this.errorno = errorno;
}
public String getResponsemsg() {
return responsemsg;
}
public void setResponsemsg(String responsemsg) {
this.responsemsg = responsemsg;
}
public String getBusid() {
return busid;
}
public void setBusid(String busid) {
this.busid = busid;
}
public String getReturnmobileno() {
return returnmobileno;
}
public void setReturnmobileno(String returnmobileno) {
this.returnmobileno = returnmobileno;
}
}
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
// get and save all data from server
Call<ResponseBody> call = apiService.getAllDataJSONFromServer(local_vcode, local_cvcode, pckgName);
call.enqueue(new Callback<ResponseBody>() {
#SuppressWarnings("ConstantConditions")
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responsebody) {
try {
String response = responsebody.body().string();
serverData = gson.fromJson(response, ServerData.class); // this will fetch data to model class ServerData
if (serverData != null) {
// do the rest here...
String vcode = serverData.getVcode();
Log.e("~~~ vode = ", vcode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
progressDialog.dismiss();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
try {
t.printStackTrace();
progressDialog.dismiss();
} catch (Exception ignored) {
}
}
});