I need to create json of this format:
{
"array": [
1482922777223,
0.014221191,
0.014221191,
0.014221191
]
}
Data.class
public class Data {
#SerializedName("array")
#Expose
private List<Float> array = null;
}
to convert object to JSON string i use gson library.
List<Float> list = new ArrayList<>();
list.add((float)1482922777223);
list.add(0.014221191);
list.add(0.014221191);
list.add(0.014221191);
Data data = new Data(list);
Gson gson = new Gson();
String json = gson.toJson(data);
Result string:
{
"array": [
1.4829219E12, <--- HOW TO GET HERE 1482922777223?
0.014221191,
0.014221191,
0.014221191
]
}
Please help!
You need to register TypeAdapter for Float values.
E.g:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Float.class, new JsonSerializer<Float>() {
#Override
public JsonElement serialize(final Float src, final Type typeOfSrc, final JsonSerializationContext context) {
BigDecimal value = BigDecimal.valueOf(src);
return new JsonPrimitive(value);
}
});
Gson gson = gsonBuilder.create();
String json = gson.toJson(data);
Output :
{
"array": [
1482922777223,
0.014221191,
0.014221191,
0.014221191
]
}
Related
Currently I am using Gson to convert an object to json
Custom Adapter
public class MyDataMsgSerializer implements JsonSerializer<MyDataMsg>, JsonDeserializer<MyDataMsg>{
private static Gson gson;
static {
try {
gson = new GsonBuilder().registerTypeHierarchyAdapter(BsCal.class, new CalendarSerializer()).setDateFormat("dd-MM-yyyy HH:mm:ss").serializeNulls().create();
} catch (Exception e) {
}
}
#Override
public JsonElement serialize(MyDataMsgsrc, Type typeOfSrc, JsonSerializationContext context) {
JsonElement jsonSubscription = gson.toJsonTree(src, typeOfSrc);
return jsonSubscription;
}
#Override
public MyDataMsg deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return gson.fromJson(json, MyDataMsg.class);
}
}
private String convertObjToJson(MyDataMsg myDataMsg) {
Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(BsCal.class, new CalendarSerializer()).setDateFormat("dd-MM-yyyy HH:mm:ss")
.registerTypeHierarchyAdapter(MyDataMsg.class, new MyDataMsgSerializer()).serializeNulls()
.create();
String jsonToString = gson.toJson(myDataMsg);
LOGGER.info("Converted Json Object {}", jsonToString);
return jsonToString;
}
output:
"myDataMsg": {
"emplId": "15163",
"mnthCd": "202211",
"empltype": "M",
"workingCd": "wfh",
"btchnm": "0499",
"shift": "1",
"shiftStTm": {
"dateTime": "2022-11-30 00:00:00”,
"timeInMs": 1669766400000
},
"actncd": "UPDATE",
"IsLead": null,
"nightSf": "2",
"overtm": null,
"totalOverTm": null,
"ExtraSal": "630"
}
Currently the 'shiftStTm' is being generated as below
"shiftStTm": {
"dateTime": "2022-11-30 00:00:00",
"timeInMs": 1669766400000
},
I want it to be generated as this (key value)
"shiftStTm":"2022-11-30 00:00:00"
could any one help me here to format it to key value using GsonBuilder??
I am using GsonBuilder to convert MyDataMsg to json In which the date is formatting as object instead of key vale, could you please help me to fix the issue?
My Rest API is returning the following response, in which only the inner list is required, all data shall be discarded:
{
"meta": [],
"links": [],
"body": [
{
"meta": [],
"links": [],
"body": {
"field1": "value1",
"fieldn": "valuen"
} // <-----
},
{
"meta": [],
"links": [],
"body": {
"field1": "value1",
"fieldn": "valuen"
} // <-----
}
]
}
Is there any way in Gson or another other java library to fetch an array of the body or a straightforward way of doing that? Or maybe even using standard of java 8?
Or, should I use a standard iterator as follows:
//Old way to do this
JSONArray BodyArr = (JSONArray) jsonObject.get("Body");
Iterator<JSONObject> itBody = BodyArr.iterator();
int teller = 0;
while (itBody.hasNext()) {
JSONObject bodyObj = itBody.next();
JSONObject body = (JSONObject) bodyObj.get("Body");
}
Also in mysql we have way to do that using notation ($.body.body[] etc.). Is there any notational way to fetch the object
I think we have a nicely written article on this.
Json object iteration
If you have a class that represents an object in the array, then you can deserialize the JSONArray to an array of that class using public <T> T fromJson(JsonElement json, java.lang.Class<T> classOfT) throws JsonSyntaxException on the Gson class:
class BodyItem {
public String[] meta;
public String[] links;
public String field1;
public String fieldn;
}
public BodyItem[] getBodyItems(final Gson gson, final JsonObject jsonObject) {
final JsonElement body = jsonObject.get("body");
return gson.fromJson(body, BodyItem[].class);
}
public static void main(final String[] args) {
final String response = "<your REST API JSON response>";
final Gson gson = new Gson();
final JsonObject jsonObject = gson.fromJson(response, JsonObject.class);
final BodyItem[] bodyItems = getBodyItems(gson, jsonObject);
}
If you want a more notational way of accessing fields in Gson objects, you can use JsonObject's convenience accessors:
JsonArray getAsJsonArray(java.lang.String memberName)
JsonObject getAsJsonObject(java.lang.String memberName)
JsonPrimitive getAsJsonPrimitive(java.lang.String memberName)
And then with a JsonArray, you can iterate with for (final JsonElement element : jsonArray) or .forEach, and you can get JsonElements with the JsonElement get(int i) accessor.
So, say you had your original JsonObject response and wanted to get the value of body.field1 in the second element of the body list, you might do:
String value = jsonObject
.getAsJsonArray("body")
.get(1)
.getAsJsonObject()
.getAsJsonObject("body")
.getAsJsonObject("field1");
I have a Json like below:
{
"searchResults": {
"searchCriteria": {
"location": {
"originalLocation": null
},
"startAndEndDate": {
"start": "2016-10-06T00:00:00",
"end": "2016-10-09T00:00:00"
},
"solution": [
{
"resultID": "O1MDc1MD",
"selected": false,
"charges": {
"localCurrencyCode": "USD",
"averagePricePerNight": 153
},
"starRating": 3.5
},
{
"resultID": "0MDc1MD",
"selected": false,
"charges": {
"localCurrencyCode": "USD",
"averagePricePerNight": 153
},
"starRating": 3.5
}
....
I have class with attributes starRating and averagePricePerNight which essentially formulates into my POJO.
class ResponseModel {
Int starRating; Int averagePricePerNight
}
I want to parse this JSON and return a List containing :
List(ResponseModel(3.5,900), ResponseModel(3.5,100), ResponseModel(4.5,1000))
I tried to get the json as a List but then i am unable to find examples to get two elements from JSon.
You can write a custom deserializer:
class Deserializers {
public static ResponseModel responseModelDeserializer(JsonElement json, Type typeOfT,
JsonDeserializationContext context) {
JsonObject obj1 = json.getAsJsonObject();
JsonObject obj2 = obj1.get("charges").getAsJsonObject();
double starRating = obj1.get("starRating").getAsDouble();
int averagePricePerNight = obj2.get("averagePricePerNight").getAsInt();
return new ResponseModel(starRating, averagePricePerNight);
}
}
Register it when building Gson:
Gson gson = new GsonBuilder()
.registerTypeAdapter(ResponseModel.class,
(JsonDeserializer<ResponseModel>) Deserializers::responseModelDeserializer
// ^^^ Cast is needed because the parameter has type Object
)
.create();
(Other options include, besides a method reference, are; lambda, anonymous class, or just a regular class. But this one is my favourite.)
Parse your json:
// Get root json object
JsonObject root = new JsonParser().parse(input).getAsJsonObject();
Type tt = new TypeToken<List<ResponseModel>>() {}.getType();
// Get array
List<ResponseModel> mo = gson.fromJson(root.get("solution"), tt);
System.out.println(mo); // [3.5 : 153, 3.5 : 153]
Where ResponseModel is:
class ResponseModel {
private final double starRating;
private final int averagePricePerNight;
public ResponseModel(double starRating, int averagePricePerNight) {
this.starRating = starRating;
this.averagePricePerNight = averagePricePerNight;
}
#Override
public String toString() {
return String.format("%s : %s", starRating, averagePricePerNight);
}
}
I made starRating a double since it seems to be one in your example.
Am retrieving information from my SQLite database to display on CardView
My SQLite database structure is SQLite DB
My class is
public class ServiceRequest{
public String reqid;
public String name;
public String branch;
public Date date;
public Date time;
public String services;
//Getter and setter
.............
.............
}
I can convert this to JSON format using
List<ServiceRequest> reqs = getAllReqs();
List<ServiceRequest> jobservList = new ArrayList<>();
for (ServiceRequest access : reqs) {
ServiceRequest ob = new ServiceRequest();
ob.setId(access.getId());
ob.setBranch(access.getBranch());
ob.setName(access.getName());
ob.setDate(access.getDate());
ob.setTime(access.getTime());
ob.setServices(access.getServices());
jobservList.add(ob);
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json2 = gson.toJson(jobservList);
return json2;
but my desired JSONObject format is
{
"100": {
"name": "Rahul Suresh",
"branch": "Koramangala",
"phNumber":"123456",
"date": "2016-08-06",
"time": "16:00",
"reqServices": "Loans"
},
"200": {
"name": "Sidh",
"branch": "Jayanagar",
"phNumber":"182694",
"date": "2016-08-12",
"time": "11:00",
"reqServices": "OpenAcc,SafeDeposit"
}
}
so that I will get one whole JSON object with a single call
JSONObject jb = (JSONObject) jsonObject.get(Integer.toString(id));
100,200 are 'reqid' s
It's possible to achieve this using string builder. But is there any other ways to implement this like using an object mapper along with a class or something..?
If you would like to form the JSON you have shown, you could "pull out" the ID into a HashMap key, then set the value to be your object.
I can't remember how Gson handles the conversion of the object values in the map, but this is the general idea
List<ServiceRequest> reqs = getAllReqs();
HashMap<Integer, ServiceRequest> map = new HashMap<Integer, ServiceRequest>();
for (ServiceRequest access : reqs) {
map.put(access.getId(), access);
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json2 = gson.toJson(map); // TODO: Not sure if this will work
return json2;
I am new to stackoverflow.
I am creating an Java application which it will get data from a web server. The data is in json format. Example"
[
{
"item_name": "Adame",
"item_type": "Special",
"item": "Chestplate",
"item_min_lvl": "50",
"enchantment": {
"health": "0.3",
"dam": "24%",
"life": "0.1",
"xp": "24%",
"loot": "22%"
},
"def": "73"
},
{
"item_name": "Sticks'",
"item_type": "Unique",
"item": "Stick",
"item_min_lvl": "4",
"enchantment": {
"health": "0.6",
"mana": "1",
"dam": "12%",
"life": "0.3",
"xp": "17%",
"loot": "17%"
},
"min_dam": "39",
"max_dam": "34"
}
]
I know how to deserialize json using Gson. As you can see, it's started with [. I never deserialize this case before. Also, the json data is not the same(e.g. enchantment). I also searched in Google but I can't find any similar case. Can anyone help me with the code?
Try with this code. You will get the answer of your question. It's an List with 2 items.
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(new File("resources/json1.txt")));
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<MyJSON>>() {
}.getType();
List<MyJSON> list = gson.fromJson(builder.toString(), listType);
// you can try this form as well
// MyJSON[] list = gson.fromJson(builder.toString(), MyJSON[].class);
for (MyJSON json : list) {
System.out.println(json.toString());
}
...
class MyJSON {
String item_name;
String item_type;
String item;
String item_min_lvl;
Enchantment enchantment;
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("\nitem_name:").append(item_name);
builder.append("\nitem_type:").append(item_type);
builder.append("\nitem:").append(item);
builder.append("\nitem_min_lvl:").append(item_min_lvl);
builder.append("\n\nEnchantment Details:");
builder.append("\nhealth:").append(enchantment.health);
builder.append("\ndam:").append(enchantment.dam);
builder.append("\nlife:").append(enchantment.life);
builder.append("\nxp:").append(enchantment.xp);
builder.append("\nloot:").append(enchantment.loot);
return builder.toString();
}
}
class Enchantment {
String health;
String dam;
String life;
String xp;
String loot;
}
output:
item_name:Adame
item_type:Special
item:Chestplate
item_min_lvl:50
Enchantment Details:
health:0.3
dam:24%
life:0.1
xp:24%
loot:22%
item_name:Sticks'
item_type:Unique
item:Stick
item_min_lvl:4
Enchantment Details:
health:0.6
dam:12%
life:0.3
xp:17%
loot:17%
EDIT
The structure of each entry is not same hence you can't use POJO for this type of JSON.
Simply use ArrayList<Map<String, Object>> and access the value based on key from the map.
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Map<String, Object>>>() {
}.getType();
ArrayList<Map<String, Object>> list = gson.fromJson(builder.toString(), listType);
for (Map<String, Object> json : list) {
for (String key : json.keySet()) {
System.out.println(key + ":" + json.get(key));
}
System.out.println("===========");
}
output:
item_name:Adame
item_type:Special
item:Chestplate
item_min_lvl:50
enchantment:{health=0.3, dam=24%, life=0.1, xp=24%, loot=22%}
def:73
===========
item_name:Sticks'
item_type:Unique
item:Stick
item_min_lvl:4
enchantment:{health=0.6, mana=1, dam=12%, life=0.3, xp=17%, loot=17%}
min_dam:39
max_dam:34
===========
This is actually valid in Java and with GSON:
YourObject[] locs = gson.fromJson (someJsonString, YourObject[].class);
It'll parse and return an array of YourObject. Just create Java Classes that represent your JSON objects, and replace the placeholders as necessary.
EDIT:
As Braj said before, you can create a fully formed POJO, including the other, (non-symmetrical) attributes (I'm borrowing the code from from Braj's answer here):
//... snip ...
class MyJSON
{
String item_name;
String item_type;
String item;
String item_min_lvl;
Enchantment enchantment;
// Heres the other attributes
String min_dam;
String max_dam;
}
//... snip ...
GSON will parse it and set the values to null if they aren't provided in the original JSON.
However, from the other question, it seems that the JSON (Java - JSON Parser Error) for enchantment is provided inconsistently, so this will cause issues. I would recommend sending JSON for enchantment as an array for consistency, then you could structure your POJO as:
//... snip ...
class MyJSON
{
String item_name;
String item_type;
String item;
String item_min_lvl;
Enchantment[] enchantment;
// Heres the other attributes
String min_dam;
String max_dam;
}
//... snip ...