如何将JSON映射到java模型类 [英] how to map a JSON to a java model class

查看:1061
本文介绍了如何将JSON映射到java模型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 JSON obj映射到一个类,并将其数组映射到中的 ArrayList Android ,它也应该拥有所有子数据。 (也有嵌套的arraylists)我需要再次将更新的数据列表转换为 jsonobject

I need to map JSON obj to a class and its arrays to ArrayList in Android and it should have all the children data as well. (with nested arraylists too) and i need to convert updated data list again to jsonobject

my json字符串是

  {
    "type": "already_planted",
    "crops": [
      {
        "crop_id": 1,
        "crop_name": "apple",
        "crop_details": [
          {
            "created_id": "2017-01-17",
            "questions": [
              {
                "plants": "10"
              },
              {
                "planted_by": "A person"
              }
            ]
          },
          {
            "created_id": "2017-01-30",
            "questions": [
              {
                "plants": "15"
              },
              {
                "planted_by": "B person"
              }
            ]
          }
        ]
      },
      {
        "crop_id": 2,
        "crop_name": "Cashew",
        "crop_details": [
          {
            "created_id": "2017-01-17",
            "questions": [
              {
                "plants": "11"
              },
              {
                "planted_by": "c person"
              }
            ]
          }
        ]
      }
    ]
  }


推荐答案

首先,您需要创建要在其中映射JSON的类。

First of all, you need to create the class that you are going to map JSON inside.

幸运的是,有一个网站可以为你做这件事这里

Fortunately, there is a website that can do it for you here

其次,您可以使用google Gson 库,便于映射

secondly, you can use google Gson library for easy mapping

1。添加依赖关系

1. add the dependency.

        dependencies {
          compile 'com.google.code.gson:gson:2.8.2'
         }  

2。从您的对象到JSON。

        MyData data =new MyData() ; //initialize the constructor 
        Gson gson = new Gson();  
        String Json = gson.toJson(data );  //see firstly above above
        //now you have the json string do whatever.

3。从JSON到对象。

        String  jsonString =doSthToGetJson(); //http request 
        MyData data =new MyData() ; 
        Gson gson = new Gson();  
        data= gson.fromJson(jsonString,MyData.class); 
        //now you have Pojo do whatever

有关gson的更多信息,请参阅 tutorial

for more information about gson see this tutorial.

这篇关于如何将JSON映射到java模型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆