This PR is related to the article BAEL-6102 (#15855)

* This commit is related to BAEL-6102

This commit aims to add a main class for the article "Preventing Gson from Expressing Integers as Floats".

* This commit is related to BAEL-6102

This commit aims to add a test class "PreventExpressingIntAsFloatUnitTest.java" for the article "Preventing Gson from Expressing Integers as Floats".
This commit is contained in:
Mo Helmy 2024-02-12 19:44:31 +02:00 committed by GitHub
parent 5e91827680
commit 73a9ed952b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,22 @@
package com.baeldung.preventexpressingintasfloat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Hashtable;
public class Main {
public static String draft = "[{\"id\":4077395,\"field_id\":242566,\"body\":\"\"}, " +
"{\"id\":4077398,\"field_id\":242569,\"body\":[[273019,0],[273020,1],[273021,0]]}, " +
"{\"id\":4077399,\"field_id\":242570,\"body\":[[273022,0],[273023,1],[273024,0]]}]";
public static void main(String[] args) {
ArrayList<Hashtable<String, Object>> responses;
Type ResponseList = new TypeToken<ArrayList<Hashtable<String, Object>>>() {
}.getType();
responses = new Gson().fromJson(draft, ResponseList);
System.out.println(responses);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.preventexpressingintasfloat;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Hashtable;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PreventExpressingIntAsFloatUnitTest {
public String jsonString = "[{\"id\":4077395,\"field_id\":242566,\"body\":\"\"}, " +
"{\"id\":4077398,\"field_id\":242569,\"body\":[[273019,0],[273020,1],[273021,0]]}, " +
"{\"id\":4077399,\"field_id\":242570,\"body\":[[273022,0],[273023,1],[273024,0]]}]";
public String expectedOutput = "[{body=, field_id=242566, id=4077395}, " +
"{body=[[273019, 0], [273020, 1], [273021, 0]], field_id=242569, id=4077398}, " +
"{body=[[273022, 0], [273023, 1], [273024, 0]], field_id=242570, id=4077399}]";
@Test
public void givenJsonString_whenUsingsetObjectToNumberStrategyMethod_thenValidateOutput() {
Gson gson = new GsonBuilder().setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE).create();
ArrayList<Hashtable<String, Object>> responses = gson.fromJson(jsonString, new TypeToken<ArrayList<Hashtable<String, Object>>>() {
}.getType());
assertEquals(expectedOutput, responses.toString());
}
}