Gson make firebase-like json from objects

社会主义新天地 提交于 2019-12-13 01:05:01

问题


In the past a manually created as list of data, which was stored locally in a database. Now I would like to parse those data and put them through import json option into firebase dbs, but what I get doesn't look like firebase generated json.

What I get is:

[  
   {  
      "id":"id_1",
      "text":"some text"
    },
    {  
      "id":"id_2",
      "text":"some text2"
    },
    ...
]

what I want is something like this:

{  
   "id_1": {  
      "text":"some text",
      "id":"id_1"
    },
    "id_2":{  
      "text":"some text2",
      "id":"id_1"
    },
    ...
}

my Card class

class Card{
    private String id;
    private String text;

}

retrieving data

//return list of card
List<Card> cards =myDatabase.retrieveData();
Gson gson = new Gson();
String data = gson.toJson(cards);

So how I can I achieve this (it looks to me) dynamically named properties for json that look like those generated by firebase ?

EDIT: I found that gson has FieldNamingStrategy interface that can change names of fields. But it looks to me it's not dynamic as I want.

EDIT2 my temp fix was to just override toString()

 @Override
 public String toString() {
     return "\""+id+"\": {" +
                     "\"text\":" + "\""+text+"\","+
                     "\"id\":" +"\""+ id +"\","+
                     "\"type\":"+ "\""+ type +"\""+
             '}';
    }

回答1:


Your "temp fix" will store each object as a string not a object.

You need to serialize an object to get that data, not a list.

For example, using a Map

List<Card> cards = myDatabase.retrieveData();
Map<Map<String, Object>> fireMap = new TreeMap<>();
int i = 1;
for (Card c : cards) {
    Map<String, Object> cardMap = new TreeMap<>();
    cardMap.put("text", c.getText());
    fireMap.put("id_" + (i++), cardMap);
}
Gson gson = new Gson();
String data = gson.toJson(fireMap);


来源:https://stackoverflow.com/questions/47847508/gson-make-firebase-like-json-from-objects

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