【问题标题】:Generating java POCOs and populating them by reading json file, all dynamically生成 java POCO 并通过读取 json 文件来填充它们,所有这些都是动态的
【发布时间】:2019-11-20 13:15:08
【问题描述】:

我是 Android 应用程序开发的新手,我遇到了一个问题,即我需要在我的应用程序中动态创建类、定义其属性并动态填充它们。

这个动态的东西是必需的,因为 json 文件每次都会改变,点击事件会被触发,我需要填充一个 recyclerView,从该 json 文件中获取标题和相应的值。

我遇到过一些解决方案,比如使用 javassist 库和使用 hashmap(虽然我没有得到这个)。

【问题讨论】:

  • 每次都改变是什么意思?你的意思是键值对中的 JSON 键每次都会改变?
  • 是的,因为每次都会下载一个新的 json 文件。所以键和它的值,一切都会改变。
  • @RojyKumari 因此,您需要动态解析从服务器收到的 JSON 并将其解析为相应的类。像 json 对象的 Integer、Strings 和 Hashmap?
  • @RobinsGupta 不,不完全是。我需要将该 json 动态解析为 POCO

标签: java android json


【解决方案1】:

好的,我找到了。

您想在运行时解析 JSONObject 并获取它的键。而且你不知道 JSONObject 会有什么结构。

就用这个Json helperJSON HELPER

要转换 JSONObject,请使用那里给出的JsonHelper.toMap(JSONObject object)

//Now to get the keys
for ( String key : hashMapObject.keySet() ) {
    System.out.println( key );
} 




//Here hashMapObject is generated from `JsonHelper.toMap` method.

【讨论】:

    【解决方案2】:

    只需使用Retrofit 库,一切都会自动处理,非常容易Retrofit

    只需按照以下步骤使用 Retrofit

    首先下载 Retrofit 并将其集成到您的 android 项目中。

    //In your Gradle file. Add this line.
    
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    

    现在假设你想从一个 URL 实现一个Get 请求让我们说

    https://api.github.com/users/{user}/repos. 获取GitHub 上列出的所有存储库。这里{user} 将是用户名

    所以你的基本 URL 是 https://api.github.com 和路径 获取为/users/{user}/repos

    现在创建一个界面。

    public interface GitHubService {
        @GET("/users/{user}/repos")
        Call<List<Repo>> listRepos(@Path("user") String user);
    }
    
    
    
    Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com").build();
    GitHubService service = retrofit.create(GitHubService.class);
    
    //Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.
    Call<List<Repo>> repos = service.listRepos("robinskumar73");
    

    【讨论】:

    • Repo 是这里的预定义类,ryt?
    • Key:Value 对总是变化的,所以你的 Repo 必须是一些动态对象,否则它就不会工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 2023-04-03
    • 2021-12-27
    相关资源
    最近更新 更多