Parsing nested objects inside array by LoganSquare

594 Views Asked by At

I have a problem in parsing JSON received from server. In the model I have:

@JsonField(name = "skills")
private ArrayList<Skill> skills;

which has fields:

@JsonObject
public class Skill {
    @JsonField
    private int skillID;
    @JsonField
    private String name;
    ...
}

The ArrayList gets proper count of objects but all fields inside them are nulls.

JSON looks like:

{
   "skills":[
      {
         "skill":{
            "skillID":"1",
            "name":"foo"
         }
      },
      {
         "skill":{
            "skillID":"2",
            "name":"bar"
         }
      }
   ]
}

The question is: How to extract the Skill objects into ArrayList without nesting additional class (Skill)?

Maybe there is a possibility to set the "skill" name on @JsonObject annotation?

2

There are 2 best solutions below

0
On

Here I put easy solution for parsing:

ArrayList<Skill> skills;
    try{
    JSONObject jobj=new JSONObject(str);
    JSONArray jsar=jobj.getJSONArray("skills");
    for(int i=0;i<jsar.length();i++){
        JSONObject skobj=jsar.getJSONObject(i);
        JSONObject sksub=skobj.getJSONObject("skill");
        //in skill class objest assign name & Id using obj.getstring("Name");
        skills.add(new skill(sksub));
    }
    }catch(Exception e){
        e.printStackTrace()
    }
0
On

Please try this code very simple and fast

  ArrayList<Skill> skillsArrayList = new ArrayList<>();

and now parse the Json by using following code

 try {
        skillsArrayList=new ArrayList<>();
        JSONObject object=new JSONObject(jsonString);

        JSONArray array=object.getJSONArray("skills");
        for (int i=0;i<array.length();i++){
            JSONObject jsonObject=array.getJSONObject(i).getJSONObject("skill");

            skillsArrayList.add(new Skill(jsonObject.getInt("skillID"),jsonObject.getString("name")));
        }

        Log.e("skillItemCount",skillsArrayList.size()+"");

    } catch (JSONException e) {
        e.printStackTrace();
    }

and here is my custom class for this

 class Skill{
    int id;
    String name;

    public Skill(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}