简体   繁体   English

从后端解析JSON的问题

[英]Problem with parsing JSON from the backend

As I have been working on an Android project in which there is a need to receive JSON from the backend, I prepared the JSON in Java using Spring Boot 2.1.7. 因为我一直在研究需要从后端接收JSON的Android项目,所以我使用Spring Boot 2.1.7用Java准备了JSON

From the backend side it is ok, works. 从后端来看,还可以。 But from the Android side, I cannot parse the variable. 但是从Android的角度来看,我无法解析该变量。 When I try to parse the variable using construction: 当我尝试使用构造方法解析变量时:

JSONArray jsonArray = new JSONArray(variable);

then I recieve the information that JSONArray() in JSONArray cannot be applied to com.package.Model . 然后我收到以下信息,即JSONArray中的JSONArray()无法应用于com.package.Model I have also tried different approach to this problem: 我也尝试过其他解决此问题的方法:

Backend 后端

@RequestMapping( value = "/approachh", method = RequestMethod.GET )
@ResponseBody
public List<Categories> getList() {
    List<Categories> categoriesList = new ArrayList<>();
    categoriesList = categoriesRepository.findAll();
    return categoriesList;
}

JSON response JSON回应

{
  "List":[
    {
      "id":1,
      "categoryName":"Categories1",
      "subCategories":[
        {
          "id":1,
          "subCategoriesName":"lkjasdf"
        }
      ]
    },
    {
      "id":2,
      "categoryName":"Categories2",
      "subCategories":[
        {
          "id":2,
          "subCategoriesName":"lkjasdasdfasf"
        }
      ]
    }
  ]
}

Client (Android) 客户端(Android)


JSONArray jsonArray = new JSONArray(variable); 
// then I recieve the information that JSONArray() in JSONArray cannot be applied to com.package.Model. I have also tried different approach to this problem:

String json = "";
Gson gson = new GsonBuilder().create();
Type showType = new TypeToken<Collection<Approach>>(){}.getType();
ArrayList<Approach> approaches = gson.fromJson(json, showType);
String catName = String.valueOf(approaches.get(0).getCategoryName());

// but when I tried to receive information about the catName, there was 0.
Log.d("catName","catName" + catName);

Approach.class 方法类

public class Approach {


@SerializedName("categoryName")
@Expose
private String categoryName;

@SerializedName("subCategories")
@Expose
private List<SubCategories> subCategories;

public Approach(String categoryName, List<SubCategories> subCategories) {
    this.categoryName = categoryName;
    this.subCategories = subCategories;
}

public String getCategoryName() {
    return categoryName;
}

public void setCategoryName(String categoryName) {
    this.categoryName = categoryName;
}

public List<SubCategories> getSubCategories() {
    return subCategories;
}

public void setSubCategories(List<SubCategories> subCategories) {
    this.subCategories = subCategories;
}

} }

SubCategories.class SubCategories.class

public class SubCategories {


@SerializedName("id")
@Expose
private int id;

@SerializedName("subCategoriesName")
@Expose
private String subCategoriesName;

public int getId() {
    return id;
}

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

public String getSubCategoriesName() {
    return subCategoriesName;
}

public void setSubCategoriesName(String subCategoriesName) {
    this.subCategoriesName = subCategoriesName;
}

} }

MainActivity.class Android MainActivity.class Android

method in which I connect with retrofit to localhost to retrieve information 我与改造连接到本地主机以检索信息的方法

private void fetchhhhData() {

    compositeDisposable.add(iMyAPI.getAll()
    .subscribeOn(Schedulers.io())
    .subscribeOn(AndroidSchedulers.mainThread())
    .subscribe(new Consumer<Approach>() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void accept(Approach approach) throws Exception {


            showData(Collections.singletonList(approach));

        }
    }));

}

MainActivity.class Android MainActivity.class Android

showData() showData()

  private void showData(List<Approach> approaches) {

    JSONArray jsonArray = new JSONArray(approaches);



    for (int i=1; i<= jsonArray.length() - 1; i++) {

        try {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            String categ = jsonObject.get("List").toString();

             Log.d("categ","categ" + categ);

         //   String catName = String.valueOf(jsonObject.get("List"));


     //       String catName = jsonObject.getString("categoryName");

      //      Log.d("catName","catName" + catName);


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

    }



}

Could you please point me out, what I am doing wrong? 您能指出我,我做错了吗?

Thanks. 谢谢。

Here you have working example. 这里有工作示例。 It is much simpler if you introduce one more class CategoriesResponse (see below). 如果再引入一个类别CategoriesResponse (参见下文),则要简单得多。

Then make sure that the json argument passed to gson.fromJson(json, CategoriesResponse.class); 然后确保将json参数传递给gson.fromJson(json, CategoriesResponse.class); is actual json String or Reader or JsonObject retrieved from your endpoint. 是从端点检索的实际json字符串, ReaderJsonObject


    @Test
    public void test() {
        String json = "{\n" + "  \"List\":[\n" + "    {\n" + "      \"id\":1,\n" + "      \"categoryName"
                + "\":\"Categories1\",\n"
                + "      \"subCategories\":[\n" + "        {\n" + "          \"id\":1,\n"
                + "          \"subCategoriesName\":\"lkjasdf\"\n" + "        }\n" + "      ]\n" + "    },\n" + "    {\n"
                + "      \"id\":2,\n" + "      \"categoryName\":\"Categories2\",\n" + "      \"subCategories\":[\n"
                + "        {\n" + "          \"id\":2,\n" + "          \"subCategoriesName\":\"lkjasdasdfasf\"\n"
                + "        }\n" + "      ]\n" + "    }\n" + "  ]\n" + "}";

        Gson gson = new Gson();
        CategoriesResponse gsonResponse = gson.fromJson(json, CategoriesResponse.class);

        assertEquals(2, gsonResponse.categories.size());

    }

    public class Approach {

        @SerializedName("categoryName") @Expose private String categoryName;
        @SerializedName("subCategories") @Expose private List<SubCategories> subCategories;

        public Approach(String categoryName, List<SubCategories> subCategories) {
            this.categoryName = categoryName;
            this.subCategories = subCategories;
        }
    }

    public class SubCategories {

        @SerializedName("id") @Expose private int id;
        @SerializedName("subCategoriesName") @Expose private String subCategoriesName;
    }

    public class CategoriesResponse {

        @SerializedName("List") @Expose private List<Approach> categories;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM