How to create a java class for a JSON string where keys are variable?

我只是一个虾纸丫 提交于 2019-12-08 04:23:35

问题


The response

array (
    0 => 
    array (
      'time_start' => 1252652400,
      'time_stop' => 1252911600,
      'stats' => 
      array (
        6002306163363 => 
        array (
          'id' => 6002306163363,
          'impressions' => '6713',
          'clicks' => '7',
          'spent' => '593',
          'actions' => '1',
        ),
      ),
    ),
  )

data is shown in facebook api of rest/ads.getAdGroupStats.

I am not able to convert the stats part to a Java class, Where the 6002306163363 is a variable and similarly could have many more mappings. Below is the full result for three ads 123456,23456,34567.

[
  {
    "time_start": 0,
    "time_stop": 1285224928,
    "stats": {
      "123456": {
        "id": 123456,
        "impressions": 40,
        "clicks": 0,
        "spent": 0,
        "social_impressions": 0,
        "social_clicks": 0,
        "social_spent": 0
      },
      "23456": {
        "id": 23456,
        "impressions": 3,
        "clicks": 0,
        "spent": 0,
        "social_impressions": 0,
        "social_clicks": 0,
        "social_spent": 0
      },
      "34567": {
        "id": 34567,
        "impressions": 211457,
        "clicks": 84,
        "spent": 6898,
        "social_impressions": 124,
        "social_clicks": 0,
        "social_spent": 0
      }
    }
  }
]

I have to make a Java class which could map to the above JSON and not able to do so. Can anyone please help me here?

Update : I am getting this data from facebook and in the api that we are using requires class, so that the returned json could be mapped. I have only control to create a class so that api internally map this out. I need the format of the java class required.


回答1:


You need a hashmap or something similar to deal with those numerical keys.

public class GroupStats {
   long time_start;
   long time_stop;
   HashMap<GroupAccount> stats;
}

public class GroupAccount {
   long id;
   int impressions;
   int clicks;
   int spent;
   int social_impressions;
   int social_spent;
}



回答2:


I'm Mark Allen (RestFB maintainer). Version 1.6 should address this with the new option to map to the built-in JsonObject type - check out http://restfb.com for an example.



来源:https://stackoverflow.com/questions/3776699/how-to-create-a-java-class-for-a-json-string-where-keys-are-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!