JSON 正在解析二维数组中的数据

JSON Parsing data from 2 dimension array

我需要从 house 数组中获取数据,我的 json 文件看起来像,

{
"mydata": {
"totalRoads": "13",
"noOfHouse": "5",
"house": [
  {
    "road": "1",
    "right": [
      {
        "houseID": "A3",
        "isPainted": "false",
        "ownerGender": "female"
      },
      {
        "houseID": "A4",
        "isPainted": "true",
        "ownerGender": "female"
      }
    ],
    "left": [
      {
        "houseID": "A1",
        "isPainted": "false",
        "ownerGender": "female"
      },
      {
        "houseID": "A2",
        "isPainted": "false",
        "ownerGender": "female"
      }
    ]
  },
  {
    "road": "2",
    "right": [
      {
        "houseID": "B3",
        "isPainted": "false",
        "ownerGender": "male"
      },
      {
        "houseID": "B4",
        "isPainted": "true",
        "ownerGender": "male"
      }
    ],
    "left": [
      {
        "houseID": "B1",
        "isPainted": "true",
        "ownerGender": "male"
      },
      {
        "houseID": "B2",
        "isPainted": "true",
        "ownerGender": "male"
      }
    ]
  },
  {
    "road": "3",
    "right": [
      {
        "houseID": "C3",
        "isPainted": "false",
        "ownerGender": "male"
      },
      {
        "houseID": "C4",
        "isPainted": "false",
        "ownerGender": "male"
      }
    ],
    "left": [
      {
        "houseID": "C1",
        "isPainted": "true",
        "ownerGender": "male"
      },
      {
        "houseID": "C2",
        "isPainted": "false",
        "ownerGender": "male"
      }
    ]
  }
]
}
}

我只是这样尝试解析来自 json、

的数据
InputStream inputStream = getResources().openRawResource(R.raw.house_details);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int ctr;
    try {
        ctr = inputStream.read();
        while (ctr != -1) {
            byteArrayOutputStream.write(ctr);
            ctr = inputStream.read();
        }
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.v("House Data", byteArrayOutputStream.toString());
    try {
        JSONObject jObject = new JSONObject(
                byteArrayOutputStream.toString());
        JSONObject jObjectResult = jObject.getJSONObject("mydata");
        JSONArray jArray = jObjectResult.getJSONArray("house");
        String house_ID = "";
        boolean is_painted = false;
        String owner_gender = "";
        ArrayList<String[]> data = new ArrayList<String[]>();
        for (int i = 0; i < jArray.length(); i++) {
            house_ID = jArray.getJSONObject(i).getString("houseID");
            is_painted = jArray.getJSONObject(i).getBoolean("isPainted");
            owner_gender = jArray.getJSONObject(i).getString("ownerGender");
            Log.v("house_ID", house_ID);
            Log.v("is_painted", String.valueOf(is_painted));
            Log.v("owner_gender", owner_gender);
            data.add(new String[] { house_ID, String.valueOf(is_painted), owner_gender });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

但我无法得到我所期望的,请帮助我从 json 获取所有数据。

您正在尝试访问从 househouseId 的数据,但您必须先通过 rightleft 结构。

您好,您的 json 无效

           {
"mydata": {
  "totalRoads": "13",
  "noOfHouse": "5",
  "house": [
    {
      "road": "1",
      "right": [
        {
          "houseID": "A3",
          "isPainted": "false",
          "ownerGender": "female"
        },
        {
          "houseID": "A4",
          "isPainted": "true",
          "ownerGender": "female"
        }
      ],
      "left": [
        {
          "houseID": "A1",
          "isPainted": "false",
          "ownerGender": "female"
        },
        {
          "houseID": "A2",
          "isPainted": "false",
          "ownerGender": "female"
        }
      ]
    },
    {
      "road": "2",
      "right": [
        {
          "houseID": "B3",
          "isPainted": "false",
          "ownerGender": "male"
        },
        {
          "houseID": "B4",
          "isPainted": "true",
          "ownerGender": "male"
        }
      ],
      "left": [
        {
          "houseID": "B1",
          "isPainted": "true",
          "ownerGender": "male"
        },
        {
          "houseID": "B2",
          "isPainted": "true",
          "ownerGender": "male"
        }
      ]
    },
    {
      "road": "3",
      "right": [
        {
          "houseID": "C3",
          "isPainted": "false",
          "ownerGender": "male"
        },
        {
          "houseID": "C4",
          "isPainted": "false",
          "ownerGender": "male"
        }
      ],
      "left": [
        {
          "houseID": "C1",
          "isPainted": "true",
          "ownerGender": "male"
        },
        {
          "houseID": "C2",
          "isPainted": "false",
          "ownerGender": "male"
        }
      ]
    }
    ]
}
}


  try {
    JSONObject jObject = new JSONObject(
            byteArrayOutputStream.toString());
    JSONObject jObjectResult = jObject.getJSONObject("mydata");
    JSONArray jArray = jObjectResult.getJSONArray("house");
    String house_ID = "";
    boolean is_painted = false;
    String owner_gender = "";
    ArrayList<String[]> data = new ArrayList<String[]>();
    for (int i = 0; i < jArray.length(); i++) {

        JSONObject obj= jArray.getJSONObject(i);
        JSONArray right = obj.getJSONArray("right");
        JSONArray left= obj.getJSONArray("left");

        for(int j=0;j<right.length();j++)
         {

        house_ID = right.getJSONObject(j).getString("houseID");
        is_painted = right.getJSONObject(j).getBoolean("isPainted");
        owner_gender = right.getJSONObject(j).getString("ownerGender");
        Log.v("house_ID", house_ID);
        Log.v("is_painted", String.valueOf(is_painted));
        Log.v("owner_gender", owner_gender);
        data.add(new String[] { house_ID, String.valueOf(is_painted), 
        owner_gender });
              }

        for(int j=0;j<left.length();j++)
         {

        house_ID = left.getJSONObject(j).getString("houseID");
        is_painted = left.getJSONObject(j).getBoolean("isPainted");
        owner_gender = left.getJSONObject(j).getString("ownerGender");
        Log.v("house_ID", house_ID);
        Log.v("is_painted", String.valueOf(is_painted));
        Log.v("owner_gender", owner_gender);
        data.add(new String[] { house_ID, String.valueOf(is_painted), 
        owner_gender });
              }

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

您可以使用 Gson 库从 Json 简单的方法中获取数据,您的结构将像这样

public class Response{

    @SerializedName("mydata")
    private Mydata mydata;

    public void setMydata(Mydata mydata){
        this.mydata = mydata;
    }

    public Mydata getMydata(){
        return mydata;
    }

    @Override
    public String toString(){
        return 
            "Response{" + 
            "mydata = '" + mydata + '\'' + 
            "}";
        }
}

public class Mydata{

    @SerializedName("totalRoads")
    private String totalRoads;

    @SerializedName("noOfHouse")
    private String noOfHouse;

    @SerializedName("house")
    private List<HouseItem> house;

    public void setTotalRoads(String totalRoads){
        this.totalRoads = totalRoads;
    }

    public String getTotalRoads(){
        return totalRoads;
    }

    public void setNoOfHouse(String noOfHouse){
        this.noOfHouse = noOfHouse;
    }

    public String getNoOfHouse(){
        return noOfHouse;
    }

    public void setHouse(List<HouseItem> house){
        this.house = house;
    }

    public List<HouseItem> getHouse(){
        return house;
    }

    @Override
    public String toString(){
        return 
            "Mydata{" + 
            "totalRoads = '" + totalRoads + '\'' + 
            ",noOfHouse = '" + noOfHouse + '\'' + 
            ",house = '" + house + '\'' + 
            "}";
        }
}
public class HouseItem{

    @SerializedName("road")
    private String road;

    @SerializedName("left")
    private List<LeftItem> left;

    @SerializedName("right")
    private List<RightItem> right;

    public void setRoad(String road){
        this.road = road;
    }

    public String getRoad(){
        return road;
    }

    public void setLeft(List<LeftItem> left){
        this.left = left;
    }

    public List<LeftItem> getLeft(){
        return left;
    }

    public void setRight(List<RightItem> right){
        this.right = right;
    }

    public List<RightItem> getRight(){
        return right;
    }

    @Override
    public String toString(){
        return 
            "HouseItem{" + 
            "road = '" + road + '\'' + 
            ",left = '" + left + '\'' + 
            ",right = '" + right + '\'' + 
            "}";
        }
}

house_ID = jArray.getJSONObject(i).getString("houseID"); // WRONG WAY

我猜JSONException会发生。

你应该创建两个 FOR loop.

 for (int i = 0; i < jArray.length(); i++) 
 {
    JSONObject _jOBJ = jArray.getJSONObject(i);
    JSONArray jsonArray = _jOBJ.getJSONArray("right");
       for (int j = 0; j < jsonArray.length(); j++) 
       {
       JSONObject _jOBJCHILD = jsonArray.getJSONObject(j);
       String str_HOUSEID = _jOBJCHILD.getString("houseID");

       }
 }

houseID 在右数组中,不在 house 数组中。

试试这个:

    JSONObject jObject = new JSONObject(byteArrayOutputStream.toString());
    JSONObject jObjectResult = jObject.getJSONObject("mydata");
    JSONArray jArray = jObjectResult.getJSONArray("house");

            String house_ID = "";
            boolean is_painted = false;
            String owner_gender = "";
            ArrayList<String[]> data = new ArrayList<String[]>();
            for (int i = 0; i < jArray.length(); i++) {

               JSONObject jsonObj = jArray.getJSONObject(i);
               JSONArray jsonArray = jsonObj.getJSONArray("right");
                for (int j = 0; j < jsonArray.length(); j++) 
                {

                   house_ID = jsonArray.getJSONObject(j).getString("houseID");
                   is_painted = jsonArray.getJSONObject(j).getBoolean("isPainted");
                   owner_gender = jsonArray.getJSONObject(j).getString("ownerGender");
                Log.v("house_ID", house_ID);
                Log.v("is_painted", String.valueOf(is_painted));
                Log.v("owner_gender", owner_gender);
                data.add(new String[] { house_ID, String.valueOf(is_painted), owner_gender });

               }

            }

1- 为 houseData 创建一个模型,即

public class HotelEntity {
    private String houseID;
    private String isPainted;
    private String ownerGender;
    // add getter and setter here    
}

2-从每个房屋对象的左右两侧解析数据

for (int i = 0; i < jArray.length(); i++) {
    //get the data and map it object
    Array.getJSONObject(i).getString("right");

    for {
        // add all models to list
    }

    Array.getJSONObject(i).getString("left");

    for {
        // add all models to list
    }
}

3 将其添加到您的 houseEntity 的 ArrayList 中。

此外,您可以使用 Gson 进行 json 到对象的转换。 您不必手动解析来自 json.

的数据

您可以使用

从 json 字符串创建对象

http://www.jsonschema2pojo.org/

---------------------------------com.example.Example.java----- ------------------------------

package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName("mydata")
@Expose
private Mydata mydata;

public Mydata getMydata() {
return mydata;
}

public void setMydata(Mydata mydata) {
this.mydata = mydata;
}

}

---------------------------------com.example.House.java----- ------------------------------

    package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class House {

@SerializedName("road")
@Expose
private String road;
@SerializedName("right")
@Expose
private List<Right> right = null;
@SerializedName("left")
@Expose
private List<Left> left = null;

public String getRoad() {
return road;
}

public void setRoad(String road) {
this.road = road;
}

public List<Right> getRight() {
return right;
}

public void setRight(List<Right> right) {
this.right = right;
}

public List<Left> getLeft() {
return left;
}

public void setLeft(List<Left> left) {
this.left = left;
}

}

---------------------------------com.example.Left.java----- ------------------------------

 package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Left {

@SerializedName("houseID")
@Expose
private String houseID;
@SerializedName("isPainted")
@Expose
private String isPainted;
@SerializedName("ownerGender")
@Expose
private String ownerGender;

public String getHouseID() {
return houseID;
}

public void setHouseID(String houseID) {
this.houseID = houseID;
}

public String getIsPainted() {
return isPainted;
}

public void setIsPainted(String isPainted) {
this.isPainted = isPainted;
}

public String getOwnerGender() {
return ownerGender;
}

public void setOwnerGender(String ownerGender) {
this.ownerGender = ownerGender;
}

}

------------------------------------com.example.Mydata.java----- ------------------------------

package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Mydata {

@SerializedName("totalRoads")
@Expose
private String totalRoads;
@SerializedName("noOfHouse")
@Expose
private String noOfHouse;
@SerializedName("house")
@Expose
private List<House> house = null;

public String getTotalRoads() {
return totalRoads;
}

public void setTotalRoads(String totalRoads) {
this.totalRoads = totalRoads;
}

public String getNoOfHouse() {
return noOfHouse;
}

public void setNoOfHouse(String noOfHouse) {
this.noOfHouse = noOfHouse;
}

public List<House> getHouse() {
return house;
}

public void setHouse(List<House> house) {
this.house = house;
}

}

---------------------------------com.example.Right.java----- ------------------------------

 package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Right {

@SerializedName("houseID")
@Expose
private String houseID;
@SerializedName("isPainted")
@Expose
private String isPainted;
@SerializedName("ownerGender")
@Expose
private String ownerGender;

public String getHouseID() {
return houseID;
}

public void setHouseID(String houseID) {
this.houseID = houseID;
}

public String getIsPainted() {
return isPainted;
}

public void setIsPainted(String isPainted) {
this.isPainted = isPainted;
}

public String getOwnerGender() {
return ownerGender;
}

public void setOwnerGender(String ownerGender) {
this.ownerGender = ownerGender;
}

}

你可以获得一切:

JSONObject jObject = new JSONObject(
            byteArrayOutputStream.toString());
Gson g = new Gson();
Example example = g.fromJson(jObject .toString(), Example.class);

您可以从示例中获得价值。

Mydata mydata = example.getMyData();

List<House> lstHouse = mydata.getHouse();
for (i= 0; i < lstHouse.size(); i++){
   House house = lstHouse.get(i);
   String road = house.getRoad();

   List<Right> lstRight = house.getRight();
   for (j= 0; j < lstRight .size(); j++){
      Right right = lstRight.get(j);
      String houseID = right.getHouseID();
      String isPainted = right.getIsPainted();
      String ownerGender = right.getOwnerGender();
   }


   List<Left> lstLeft = house.getLeft();
   for (k= 0; k < lstLeft .size(); k++){
      Left left= lstLeft .get(k);
      String houseID = left.getHouseID();
      String isPainted = left.getIsPainted();
      String ownerGender = left.getOwnerGender();
   }

}

希望对您的问题有所帮助!

这是一个非常接近您的实现的解决方案,但是它是正确的,并且还会读取 "left" 数组 :)

 InputStream inputStream = getResources().openRawResource(R.raw.sojson);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int ctr;
    try {
        ctr = inputStream.read();
        while (ctr != -1) {
            byteArrayOutputStream.write(ctr);
            ctr = inputStream.read();
        }
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.v("House Data", byteArrayOutputStream.toString());
    try {
        JSONObject jObject = new JSONObject(
                byteArrayOutputStream.toString());
        JSONObject jObjectResult = jObject.getJSONObject("mydata");
        JSONArray houseArray = jObjectResult.getJSONArray("house");

        String house_ID = "";
        boolean is_painted = false;
        String owner_gender = "";
        ArrayList<String[]> data = new ArrayList<String[]>();

        for (int i = 0; i < houseArray.length(); i++) {

            JSONObject ob = houseArray.getJSONObject(i);

            JSONArray rightArray = ob.getJSONArray("right");

            for (int r = 0; r < rightArray.length(); r++) {
                house_ID = rightArray.getJSONObject(r).getString("houseID");
                is_painted = rightArray.getJSONObject(r).getBoolean("isPainted");
                owner_gender = rightArray.getJSONObject(r).getString("ownerGender");
                Log.v("house_ID", house_ID);
                Log.v("is_painted", String.valueOf(is_painted));
                Log.v("owner_gender", owner_gender);
                data.add(new String[]{house_ID, String.valueOf(is_painted), owner_gender});
            }

            JSONArray leftArray = ob.getJSONArray("left");

            for (int l = 0; l < leftArray.length(); l++) {
                house_ID = leftArray.getJSONObject(l).getString("houseID");
                is_painted = leftArray.getJSONObject(l).getBoolean("isPainted");
                owner_gender = leftArray.getJSONObject(l).getString("ownerGender");
                Log.v("house_ID", house_ID);
                Log.v("is_painted", String.valueOf(is_painted));
                Log.v("owner_gender", owner_gender);
                data.add(new String[]{house_ID, String.valueOf(is_painted), owner_gender});
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

一定要使用有效的JSON:

    {  
   "mydata":{  
      "totalRoads":"13",
      "noOfHouse":"5",
      "house":[  
         {  
            "road":"1",
            "right":[  
               {  
                  "houseID":"A3",
                  "isPainted":"false",
                  "ownerGender":"female"
               },
               {  
                  "houseID":"A4",
                  "isPainted":"true",
                  "ownerGender":"female"
               }
            ],
            "left":[  
               {  
                  "houseID":"A1",
                  "isPainted":"false",
                  "ownerGender":"female"
               },
               {  
                  "houseID":"A2",
                  "isPainted":"false",
                  "ownerGender":"female"
               }
            ]
         },
         {  
            "road":"2",
            "right":[  
               {  
                  "houseID":"B3",
                  "isPainted":"false",
                  "ownerGender":"male"
               },
               {  
                  "houseID":"B4",
                  "isPainted":"true",
                  "ownerGender":"male"
               }
            ],
            "left":[  
               {  
                  "houseID":"B1",
                  "isPainted":"true",
                  "ownerGender":"male"
               },
               {  
                  "houseID":"B2",
                  "isPainted":"true",
                  "ownerGender":"male"
               }
            ]
         },
         {  
            "road":"3",
            "right":[  
               {  
                  "houseID":"C3",
                  "isPainted":"false",
                  "ownerGender":"male"
               },
               {  
                  "houseID":"C4",
                  "isPainted":"false",
                  "ownerGender":"male"
               }
            ],
            "left":[  
               {  
                  "houseID":"C1",
                  "isPainted":"true",
                  "ownerGender":"male"
               },
               {  
                  "houseID":"C2",
                  "isPainted":"false",
                  "ownerGender":"male"
               }
            ]
         }
      ]
   }
}