Reputation: 2202
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"
}]
}
Upvotes: 2
Views: 1108
Reputation: 2004
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;
}
}
Upvotes: 1
Reputation: 8282
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 (,)
}
}
Upvotes: 1