I am new to android and I have the json in structure given below. How can it be parsed using json parsing or retrofit ?
{
"1,abcd":[{
"v_id":"1"
}]
"2,efgh":[{
"v_id":"2"
}]
}
Try this
try {
JSONObject jsonObject = new JSONObject("yourresponce");
JSONArray jsonarray = jsonObject.getJSONArray("1,abcd");
for(int i=0;i<jsonarray.length();i++){
JSONObject jsonObject1 = jsonarray.getJSONObject(i);
String v_id = jsonObject1.getString("v_id");
Log.d("seelogcat","values "+v_id);
}
JSONArray jsonarray2 = jsonObject.getJSONArray("2,efgh");
for(int i=0;i<jsonarray2.length();i++){
JSONObject jsonObject1 = jsonarray2.getJSONObject(i);
String v_id = jsonObject1.getString("v_id");
Log.d("seelogcat","values "+v_id);
}
}catch (Exception e){
}
Your json is Invalid Format: your Format should be below like this
{
"1,abcd": [{
"v_id": "1"
}], // here you have to add (,)
"2,efgh": [{
"v_id": "2"
}]
}
You can check here your Json is valid or not https://jsonlint.com/
To get key separate:
Iterator<?> keys = response.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( jObject.get(key) instanceof JSONObject ) {
System.out.println(key); // here you need splint based on (,)
}
}
You have a comma (,) missing there. Check in jsonlint
{
"1,abcd": [{
"v_id": "1"
}],
"2,efgh": [{
"v_id": "2"
}]
}
Retrofit with Gson can do the rest of the work. The POJO for the response will be as follows:
public class Example {
#SerializedName("1,abcd")
#Expose
private List<_1Abcd> Abcd = null;
#SerializedName("2,efgh")
#Expose
private List<_2Efgh> Efgh = null;
public List<_1Abcd> get1Abcd() {
return Abcd;
}
public void set1Abcd(List<_1Abcd> Abcd) {
this.Abcd = Abcd;
}
public List<_2Efgh> get2Efgh() {
return Efgh;
}
public void set2Efgh(List<_2Efgh> Efgh) {
this.Efgh = Efgh;
}
}
And
public class _1Abcd {
#SerializedName("v_id")
#Expose
private String vId;
public String getVId() {
return vId;
}
public void setVId(String vId) {
this.vId = vId;
}
}
And
public class _2Efgh {
#SerializedName("v_id")
#Expose
private String vId;
public String getVId() {
return vId;
}
public void setVId(String vId) {
this.vId = vId;
}
}
Related
I would like get countynames from the API and it returns nested objects;
"countries": {
"1": {
"name": "Cyprus",
"nameTurkish": "KKTC",
"nameNative": "Kıbrıs"
},
"2": {
"name": "Turkey",
"nameTurkish": "Türkiye",
"nameNative": "Türkiye"
},
"3": {
"name": "Monaco",
"nameTurkish": "Monako",
"nameNative": "Monaco"
},
and so on there are more than 200 countries and every county has its own "NUMBER_ID". In the end I want to list all "name" information. I think I should use JsonDeserializer but unfortunately I couldn't.
The entire JSON response can be read as a JSONObject that has multiple elements in it that you can iterate through and get different data.
String jsonResponse = ""; // Put the entire JSON response as a String
JSONObject root = new JSONObject(jsonResponse);
JSONArray rootArray = root.getJSONArray("countries"); // root element of the json respons
for (int i = 0; i < rootArray.length(); i++) {
JSONObject number = rootArray.getJSONObject(i);
String country = number.getString("name"); // Get country name
// Here you can add `country` into a List
}
UPDATE:
but there is no array in my JSON file, all of them are objects, every
country is in an object and every object has its own SerializedName
You can read it into JSONOjbect, and instead of using a JSONArray, you can iterate over the length of the JSONObject as below.
try {
JSONObject root = new JSONObject(jsonResponse);
JSONObject countries = root.getJSONObject("countries");
for (int i = 1; i <= countries.length(); i++) {
JSONObject number = countries.getJSONObject(String.valueOf(i));
String country = number.getString("name"); // Get country name
// Here you can add the `country` into a List
}
} catch (JSONException e) {
e.printStackTrace();
}
try using TypeToken.
Gson gson = new Gson();
List<Country> list = gson.fromJson(gson.toJson(what_you_get_data), new TypeToken<ArrayList<Country>>(){}.getType()); //Country is VO class what you make.
Here, you can see that your data looks like HashMap, so I just tried in that way and your data parsed successfully without a glitch:
Create Pojo's:
public class Countries {
private HashMap<String, Country> countries;
public HashMap<String, Country> getCountries() { return countries; }
public void setCountries(HashMap<String, Country> countries) { this.countries = countries; }
}
public class Country {
private String name;
private String nameTurkish;
private String nameNative;
public String getName() { return name; }
public void setName(String name) { this.name = name;}
public String getNameTurkish() { return nameTurkish; }
public void setNameTurkish(String nameTurkish) { this.nameTurkish = nameTurkish; }
public String getNameNative() { return nameNative; }
public void setNameNative(String nameNative) { this.nameNative = nameNative; }
}
Create a Gson Object and parse it:
Gson gson = new Gson();
// Countries Object
Type testC = new TypeToken<Countries>(){}.getType();
Countries ob = gson.fromJson(test, testC);
String newData = gson.toJson(ob.getCountries());
System.out.println("New Data: "+newData);
// All country in HashMap
Type country = new TypeToken<HashMap<String, Country>>(){}.getType();
HashMap<String, Country> countryHashMap = gson.fromJson(newData, country);
// Print All HashMap Country
for (Map.Entry<String, Country> set : countryHashMap.entrySet()) {
System.out.println("==> "+set.getKey() + " = " + set.getValue());
}
Output:
I/System.out: ==> 1 = Country{name='Cyprus', nameTurkish='KKTC', nameNative='Kıbrıs'}
I/System.out: ==> 2 = Country{name='Turkey', nameTurkish='Türkiye', nameNative='Türkiye'}
I/System.out: ==> 3 = Country{name='Monaco', nameTurkish='Monako', nameNative='Monaco'}
I am trying to parse json result without array name. Here is my json response:
[
{
"Id": 2293,
"Name": "Dr.",
"Active": true
},
{
"Id": 2305,
"Name": "Mr.",
"Active": true
},
{
"Id": 2315,
"Name": "Mrs.",
"Active": true
}
]
How to parse this using com.squareup.retrofit2:retrofit:2.1.0 library?
Create One Class Like,
class Test {
public List<TestValue> testValues;
}
Then call API,
Call<List<Test>> getTestData(#Field("xyz") String field1);
Call <List<Test>> call = service.getTestData("val");
call.enqueue(new Callback<List<Test>>() {
#Override
public void onResponse(Call<List<Test>> call, Response<List<Test>>
response) {
List<Test> rs = response.body();
}
#Override
public void onFailure(Call<List<Test>> call, Throwable t) {
}
});
User Your Model class, this is only for example purpose.
Normally you can parse as
String response = "[{"Id": 2293,"Name": "Dr.","Active": true},{"Id": 2305,"Name": "Mr.","Active": true},{"Id": 2315,"Name": "Mrs.","Active": true}]";
try {
JSONArray ja = new JSONArray(response);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
String id = jo.getString("Id");
String name = jo.getString("Name");
String active = jo.getString("Active");
}
} catch (JSONException e) {
e.printStackTrace();
}
If you want to parse it using Model Class then your Model Class will be for Retrofit
class Response
{
#SerializedName("Id")
#Expose
private String id;
#SerializedName("Name")
#Expose
private String name;
#SerializedName("Active")
#Expose
private String active;
}
and define Callback for retrofit like that
Call<List<Meeting>> getMeetings(#Field String data );
Hope this will help
how to deserialize below string in android. I have tried below
String json= ls.get(j).getCwc();
Example example = new Gson().fromJson(json,Example.class);
Json
[{
"company":"gjjzh",
"AvgSal":"hjsj"
},
{
"company":"hjd",
"AvgSal":"hjd"
},
{
"company":"hm",
"AvgSal":"lk"
},
{
"company":"er",
"AvgSal":"io"
},
{
"company":"uo",
"AvgSal":"tr"
}]
String json= ls.get(j).getCwc();
Type type = new TypeToken<List<Example>>(){}.getType();
List<Example> example = new Gson().fromJson(json,type);
where Example is
public class Example {
#SerializedName("company")
#Expose
private String company;
#SerializedName("AvgSal")
#Expose
private String avgSal;
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getAvgSal() {
return avgSal;
}
public void setAvgSal(String avgSal) {
this.avgSal = avgSal;
}
}
You'll need to create a model class for the object.
Example.java
public class Example{
String company = "";
String AvgSal = "";
}
and then you need to write code as below to convert JSONArray string into List<Model>.
String json= ls.get(j).getCwc();
Type modelListType = new TypeToken<ArrayList<Example>>(){}.getType();
ArrayList<Example> modelList = new Gson().fromJson(json, modelListType);
This will convert JSONArray into ArrayList.
This question already has answers here:
Parsing JSON object in android
(5 answers)
Closed 4 years ago.
I am trying to parse the following API data. I just have to use the start time, end time, location and event name inside my app. I have never parse this type of data before. Hitting the API URL and getting a response is working fine, I just need help in parsing.
I have tried these solutions but it didn't work.
parsing JSON 2 arrays (embedded) in Android
How to Parsing JSON (Two Dimensional) array Object in android?
How to parse JsonArray and JSON Object having two keys and values in android?
Ask Android parsing JSON multiple arrays.
JSON:
[
{
"end": {
"endDate": "2018-03-09",
"endTime": "03:00",
"_id": "5a901a7d9fee7d156d594b04"
},
"location": "Dance Tent",
"start": {
"startDate": "2018-03-09",
"startTime": "02:00",
"_id": "5a901a7d9fee7d156d594b05"
},
"announcementName": "Jumanji Dance Party"
}
]
Code:
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int index = 0; index < response.length(); index++) {
try {
JSONObject jsonObject = response.getJSONObject(index);
String fullName = jsonObject.getString("startTime");
String about = jsonObject.getString("announcementName");
String artistType = jsonObject.getString("endTime");
String link = jsonObject.getString("location");
//String avatar = jsonObject.getString("avatar");
Annoucement_Day_One artistInfoGetter=new Annoucement_Day_One( fullName,about, artistType, link );
annoucementDayOneList.add(artistInfoGetter);
wednesdayAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("ERRROR RES: ", error.toString());
myInstance.dismiss();
}
});
requestQueue.add(jsonArrayRequest);
Try this
try {
JSONArray jsonArray= new JSONArray(response);
for (int i=0;i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String location=object.getString("location");
String announcementName=object.getString("announcementName");
JSONObject end=object.getJSONObject("end");
String endDate=end.getString("endDate");
String endTime=end.getString("endTime");
String id=end.getString("_id");
JSONObject start=object.getJSONObject("start");
String startDate=start.getString("startDate");
String startTime=start.getString("startTime");
String start_id=start.getString("_id");
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this ,
for (int index = 0; index < response.length(); index++) {
try {
JSONObject jsonObject = response.getJSONObject(index);
JSONObject startJson = jsonObject.getJSONObject("start");
String startTime = startJson.getString("startTime");
JSONObject endJson = jsonObject.getJSONObject("end");
String endTime = endJson.getString("endTime");
String announcementName = jsonObject.getString("announcementName");
String location = jsonObject.getString("location");
} catch (JSONException e) {
e.printStackTrace();
}
}
ArrayList<Holder1> arrayList = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(response);
for(int index = 0 ;index < jsonArray.length() ; index++){
JSONObject jsonObject1 = jsonArray.getJSONObject(index);
//make a holder for end, location, start,announcementName
Holder1 holder = new Holder1();
holder.setLocation(jsonObject1.optString("location"));
holder.setAnnouncementName(jsonObject1.optString("announcementName"));
//------------
JSONObject jsonObjectEnd =jsonObject1.getJSONObject("end");
holder.setEndDate(jsonObjectEnd.optString("endDate"));
holder.setEndTime(jsonObjectEnd.optString("endTime"));
holder.setEndID(jsonObjectEnd.optString("_id"));
//--------------
JSONObject jsonObjectStart =jsonObject1.getJSONObject("start");
holder.setStartDate(jsonObjectStart.optString("startDate"));
holder.setStartTime(jsonObjectStart.optString("startTime"));
holder.setStartID(jsonObjectStart.optString("_id"));
//--------------
arrayList.add(holder);
}
} catch (JSONException e) {
e.printStackTrace();
}
Accept the answer. If you like the way i have written.
You can use the GSON library by google.
add the dependency in build.gradle.
compile 'com.google.code.gson:gson:2.8.0'
First, you have to create the model class for your JSON response. this will help you to create the model class.
public class MyPojo
{
private Start start;
private String location;
private String announcementName;
private End end;
public Start getStart ()
{
return start;
}
public String getLocation ()
{
return location;
}
public String getAnnouncementName ()
{
return announcementName;
}
public End getEnd ()
{
return end;
}
}
--------------Start.Java------------
public class Start
{
private String startTime;
private String startDate;
private String _id;
public String getStartTime ()
{
return startTime;
}
public String getStartDate ()
{
return startDate;
}
public String get_id ()
{
return _id;
}
}
------------End.Java-------------------
public class End
{
private String _id;
private String endDate;
private String endTime;
public String get_id ()
{
return _id;
}
public String getEndDate ()
{
return endDate;
}
public String getEndTime ()
{
return endTime;
}
}
Now in your onResponse method
MyPojo respnse = new Gson().fromJson(response.toString(), MyPojo.class);
you can access any method from response.Ex. response.getEnd().getEnd_date()
I am confused as to what a JSON Object is and what a JSON String is. Which part is a JSON Object, and which is a JSON String?
JSON example 1:
{
"abc":"v1",
"def":"v2"
}
JSON example 2:
{
"res":"false",
"error":{
"code":101
}
}
Given by your first example:
try {
JSONObject obj = new JSONObject(json);
String abc = obj.get("abc");
String def = obj.get("def");
} catch (Throwable t) {
// Log something maybe?
}
Simply create a JSONObject with that string in the constructor.
JSONObject obj = new JSONObject(your_string_goes_here);
Your JSON string is the entire visual representation that you see (encoded as a string):
{
"abc":"v1",
"def":"v2"
}
You can tell where a specific JSON Object starts and ends within your string, by looking for that opening brace { and the closing brace '}'.
In your examples, this is a JSON Object:
{
"abc":"v1",
"def":"v2"
}
So is this:
{
"res":"false",
"error": {
"code":101
}
}
And this:
{
"code":101
}
Use GSON for parsing & below are the model classes for json1 & json2
public class Json1 {
/**
* abc : v1
* def : v2
*/
private String abc;
private String def;
public String getAbc() {
return abc;
}
public void setAbc(String abc) {
this.abc = abc;
}
public String getDef() {
return def;
}
public void setDef(String def) {
this.def = def;
}
}
Json2
public class Json2 {
/**
* res : false
* error : {"code":101}
*/
private String res;
/**
* code : 101
*/
private ErrorBean error;
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
public ErrorBean getError() {
return error;
}
public void setError(ErrorBean error) {
this.error = error;
}
public static class ErrorBean {
private int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
}
I have used GsonFormatter plugin for creating model classes, Use Gson, It is super easy and you dont need to parse anything
JSON comprises JSONObject & JSONArray.
Json-1 is JSONObject while JSON -2 is also JSONObject which contains another JSONObject with a key "error".JSON String is the string representation of JSONObject which you can get by JSONObject jsonObject = new JSONObject(); String jsonString = jsonObject.toString();
Data is represented in name/value pairs.
"abc":"v1"
Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma).
{
"abc":"v1",
"def":"v2"
}
Code Example:
JSONObject obj = new JSONObject(jsonStr);
String abc = obj.get("abc");
Square brackets hold arrays and values are separated by ,(comma).
{
"books": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt",
},
{
"id":"07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy",
}
]
}
Code Example:
JSONArray arrBooks = new JSONArray("books");
for (int i = 0; i<=arrBooks.length(); i++){
JSONObject objBook = arrBooks.getJSONObject(i);
String id = c.getString("id");
}