Questions tagged [gson]

Gson, developed by the tech giant Google, is an open-source framework specifically designed to efficiently convert Java objects to JSON and vice versa.

attempting to employ a custom class for storing a JSON reply

I am currently working on creating a Java class that will store a JSON response structured like this: { "Global Quote": { "01. symbol": "IBM", "02. open": "160.0000", "03. h ...

Navigating JSON with Java/Jackson

I am currently working on a Java application to parse JSON data from the Reddit API. The sample JSON data I am trying to parse is structured like this: [ { "kind": "Listing", "data": { "modhash": "1jq62oyvwe15aaba7eb18b0b4363b567a007507663 ...

Enhance your Proguard and Gson skills by transforming variable names within an arraylist

During debugging, my code works perfectly fine. However, when I release my apk with Proguard 5, it obfuscates my variables. As a result, the string generated after "Jsonifying" is also obfuscated, causing issues with my PHP script. Here's an example of my ...

Issue encountered when trying to convert Mongodb Date to Java Date

I received this JSON data from my mongoDB: { "_id" : ObjectId("4f95bbe3742b1eaa929b81ef"), "empNo" : NumberLong(10), "empName" : "abc", "joinDate" : ISODate("2012-04-23T20:30:27.421Z"), "address" : { "addNo" : NumberLong(1), "addLo ...

Tips for integrating dynamic JSON data with Retrofit in Android applications?

My current project involves developing an app that presents daily stock data to the user. However, I am facing a challenge with using retrofit for API calls due to the structure of the JSON response. It seems impractical to create a POJO for each individua ...

Is there a way to directly override Gson's predefined number converters without using delegation?

Currently, I am facing an issue with Gson while converting my JSON data to a Map. The problem arises when Gson parses integer fields as doubles instead of longs. Is there a way to make Gson parse them correctly as longs or integers without ...

Encountering an issue with GSON while attempting to convert an array of objects with

I'm trying to make a HTTP request using Retrofit that should return an array of objects, but unfortunately I'm encountering the following errors: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARR ...

Error encountered while parsing JSON data with Gson: MalformedJsonException

Hello, I am working on a project that involves parsing JSON data. However, I keep encountering a Malformed exception while trying to do so. Below is the code I'm currently using: Object listOfGroups = sthService.getSthList(); Gson gson = new ...

Hide the value of a specific key in a JSON object

Looking for assistance with masking specific fields in JSON request and response logs. I want to be able to print the JSONs in the log while avoiding displaying certain secured fields. Here is an example: Original JSON: {"username":"user1","password":"12 ...

Parsing JSON using GSON library can be done even when the keys in the JSON string are unknown

Here is an example of the JSON structure: # "trig_cond": { # "_and": { # "param1": ["op", "value1"], # "param2": ["op", "value2"], ... # }, # "_or": { # "param1": ["op", "value1"], # ...

What is the best way to load all Arraylists from the model function?

I am integrating the FlexibleAdapter library to retrieve data from a JSON API in my android studio project. public void createHolderSectionsDatabase(int size, int headers) { databaseType = DatabaseType.MODEL_HOLDERS; HeaderHolder header = null; ...

The null evaluation consistently yields a negative outcome

import org.json.JSONObject; String jsonData = "{"someKey": " + "null" + "}"; JSONObject jsonObject = new JSONObject(jsonData); Object key = jsonObject.get("someKey"); if (null == key) { ...

Gson throwing an error with an unparsable date format?

I am encountering an issue while attempting to parse JSON data with a Java POJO class. Below is the JSON and POJO structure: JSON: { "startDate": "2018-09-18T12:00:00+0000", "endDate": "2018-09-18T14:00:00+0000", "startDateAsDate": 153 ...

gson returns null if not deserialized

Issue with Gson deserialization when not handling specific fields public class Mode { @Expose(deserialize = false) public final List<String> list; public Mode(List<String> list) { this.list = list; } public List< ...

Extract specific data from a challonge.com JSON file and store it in an ArrayList using the Gson library

I am trying to extract specific values from a JSON file obtained from challonge.com. The values I need are the "id" and "name". For more information, please refer to . Here is the code snippet I am currently using: HttpClient client = HttpClients.creat ...

Loop through the properties of a JsonObject

My goal is to use Gson to iterate through the large wrapping JsonObject. I want to extract an ArrayList containing all three-digit code integers from the inner "unterfeld" objects. This should be straightforward once I can successfully iterate through the ...

Collaborating with two-way JACKSON communication channels

Apologies for my poor English; Below is the code snippet in question: @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class UserAccount implements Serializable { private static final long seria ...

The issue of parsing JSON data into objects

Consider an array scenario where the size is 1: the json data received will not contain [], for example: {"firstname":"tom"} On the other hand, when the size exceeds 1, the data received will include [], like this: [{"firstname":"tom"},{"firstname":"rob ...

What is the best way to transform a JsonWriter into a JsonObject using GSON?

Looking for assistance on converting JsonWriter to JsonObject in GSON without using any predefined object. JsonWriter writer = new JsonWriter(new FileWriter("C:\\Users\\ravr\\Desktop\\outputJSONSChema.json")); ...

What is the best way to deserialize certain fields from a Json object using Gson?

Here is the JSON string I have: [ { "channel": "/bvmt/initValues", "data": { "value": { "instrumentIds": "['TN0007250012','TN0007500010']", "instruments": "[{'mnemonic':'ADWYA','marche':'ADWYA','phaut':5.82,'open':5.82,'nb ...

Encountering a problem while attempting to parse a JSON object in Java using the

I am struggling with a JSON string that looks like this: String result={[{"id":"2","fullname":"Course 1"},{"id":"3","fullname":"Course 2"}]} In my Java code, I attempted to decode the JSON string using the following snippet: public class Courses { publ ...

Using Kotlin on the Android platform, learn how to convert a string into a JSON string

Seeking to convert a string into a JSON string using Gson. My desired outcome is to transform "email" into "{"email" : "$email"}" I have the function: fun serializeUserEmail(email: String): String { return &quo ...

Converting JSON Data to Java Object

I need some help with a specific issue I'm encountering. I have retrieved a JSON string from MongoDB and I am trying to extract all the values of 'photo' and store them in an ArrayList. Despite finding examples online, I haven't been successful in making ...

The JsonDeserializationException encountered an error while attempting to deserialize the object

When receiving data from the BackEnd, it typically looks like this: {name : String, author : String, updater : String, media : String, } Sometimes, the 'media' field can also be an array with a different structure, but unfortunately I am unable to mod ...

Utilize Gson library to effectively load an object

Apologies if this seems like a basic question, but I am facing a bit of confusion on this Monday morning. I am interested in creating a method that utilizes certain functionalities from the Gson library to load various settings Objects. Essentially, I hav ...

Gson: Omitting a field in a specific class without the use of annotations - Part 2

Currently I am working on serializing a Java object to JSON using Gson. My goal is to exclude a specific field in one class while keeping it in another. Here's a snippet of the code: Class A { var a; var b; } Class B { var a; var c; } Class C { ...

Issue with deserializing JSON using GSON

I'm running into an issue with deserializing data using the GSON library. Here's the JSON code I am attempting to deserialize: {"response": { "@service": "CreateUser", "@response-code": "100", "@timestamp": "2010-11-27T15:52:43-08:00", ...

Error caused by Gson Overflow

While attempting to convert a Json string into a Java object using the Gson library, I encountered a StackOverflowException. java.lang.StackOverflowError com.google.gson.internal.$Gson$Types.checkNotPrimitive($Gson$Types.java:431) com.google.gson ...

The error message java.lang.NumberFormatException: Unable to parse the input string: "2017-01-28 13:28:20" occurred

During the execution of my java project, I encountered an error with a Gson deserializer function. The error message states: java.lang.NumberFormatException: For input string: "2017-01-28 13:28:20" at java.lang.NumberFormatException.forInputString(NumberF ...

Gson parser failing to parse JSON data

Below is a JSON string that I am working with: [{"BranchID":1,"SecurityCode1":13,"SecurityCode2":14,"PrintHeight":10,"PrintWidth":10,"Active":true}] This is the code snippet I am using to parse the JSON data: Type t = new TypeToken<List<Setting&g ...

Issue with extraneous characters appearing during transformation from object to String using GSON

Looking to convert an array of objects into an array of strings using Google Gson? Check out this code snippet: TestFile.java public class TestFile { public String[] objectsToStrings(Object[] obj) { Gson gson = new Gson(); String[] converted = n ...

GSON encountered a JsonSyntaxException, with an expectation of a name at line 7, column 4

In my project, there is a Result class that has various properties and is intended to be returned as JSON. public class Result { public String objectid; public String dtype; public String type; public String name; public String descrip ...

Convert C# webapi date formats to Java using Gson

I have a C# webapi project that returns instances of an object called foo. The foo object in C# has two DateTime properties. I've set up my webapi to always display seven decimal places after the time. This is how it looks when serialized into JSON: { ...

Tips for utilizing GSON and showcasing data in a JSP document

I am in the process of building a web application using JSP. One of the servlet classes I have created is as follows: package managesystem; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; impor ...

Converting a hash of hashmaps to JSON format in Java

Hey there, I've got a nested object filled with hashes and lists. I'm attempting to utilize gson but it's not cooperating when the values in hashmaps are also hashmaps instead of simple strings. Map questionDetails = new HashMap<>(); questionDetails ...

Gson Library: transform JSON containing null array field into an empty array

Is there a way to instruct GSON to create an empty array instead of setting it to null when a JSON with an array field has a NULL value? Are there any specific properties or flags that can be used for this purpose? ...

Decoding a JSON array containing multiple JSON objects into an ArrayList of org.json.JSONObject instances using Gson

I have a JSON string that looks like this: { "r": [ { "pic": "1.jpg", "name": "Name1" }, { "pic": "2.jpg", "name": "Name2" }, { "pic": "3.jpg", "name": "Name3" } ] } My goal is to convert it ...

encountering issues while Deserializing a collection containing children objects of various types

I am facing an issue with deserializing a JSON packet that consists of a header (under PACKET_HEADER) and several different types of messages (under DATA). These messages have a parent class in common: //parent message class public class Message { pu ...

Guide on transforming JSON lines that have been escaped into a collection of beans

Java POJO: import android.os.Parcel; import android.os.Parcelable; import com.gongzelong.duolingowordsearch.utils.ParcelableUtils; import com.google.gson.annotations.SerializedName; import java.util.List; public class WordSearch implements Parcelable ...

verifying for incorrectly formatted object within a JSON list

I'm facing an issue where I need to convert a list of objects into an array. Everything works smoothly when the objects are in good shape, however, it becomes quite challenging to identify which one is malformed when dealing with 4000 records. Is there a w ...

Parsing CSV rows into a map using Gson

I have a JSON API response that follows a structure resembling a CSV file { "headers": ["x", "y", "z"], "row1": [10, 20, 30], "row2": [40, 50, 60] } My goal is to extract a Plain Old Java Object (POJO) for each row in this JSON object Ideall ...

Exploring Gson's method for deserializing JSON containing optional fields

I'm currently utilizing Gson for deserializing a JSON string obtained from an API using the code snippet below. Gson gson = new Gson(); Map<String, CustomDto> test = gson.fromJson(result, new TypeToken<Map<String, CustomDto>>() {}.getTyp ...

Transform into dynamic types in Java

Today, I'm facing a challenge with JSON data that consists of an array of objects. Each object in the array contains two properties: type and value. [{ "type": "Boolean", "value": false }, { "type": "String[]", "value": ["one", "two", "thr ...

Creating a specialized serializer adapter for Gson that can be utilized in .NET: a step-by-step guide

I am currently facing an issue with serializing data between a .NET Rest webservice that returns Json responses and my Java application. I am using Gson for serialization and deserialization. The problem arises when dealing with polymorphism between the t ...

How can I obtain a JSONObject as a response in REST Client?

I am currently following a tutorial at https://github.com/excilys/androidannotations/wiki/Rest%20API and I'm looking to bypass the JSON to POJO conversion process and instead work with pure JSONObject (or gson's JsonObject). What should I include in the se ...

Navigating forward slashes in JSON within a Java/Spring application: tips and tricks

In my application, I have a function that efficiently parses JSON data received through Postman and uses the GSON library to populate an object. The object is then returned as JSON to the user. However, there is one issue with this process - one of the va ...

Converting JSON data into Kotlin objects: a step-by-step guide

Having a sample of an existing JSON, my challenge lies in converting it to Kotlin. As I am relatively new to Kotlin and have been studying various tutorials, I have yet to come across examples as complex as this. Here is the JSON: { "mobile": { "id": ...

Decoding the Gson: Unraveling the Purpose Behind Parsing Intricate Dynamic Data

My current project involves working on an Android application that receives a large amount of dynamic JSON data. Initially, I wrote my custom methods to handle this using the standard org.json packages, but I found it to be messy and plagued with bugs. Af ...

Facing a Null Pointer Exception when Deserializing Gson?

When attempting to parse JSON data in order to extract certain values, I encountered a particular issue. { "username":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2a1babdb0babba692b5bfb3bbbefcb1bdbf">[email protect ...

Utilize Gson in Kotlin to Parse JSON with Nested Objects

I am attempting to transform the JSON below into a list data object: [ { "type": "PHOTO", "id": "pic1", "title": "Photo 1", "dataMap": {} }, { "type": ...

Changing Json date format to a Java date object

In my JSON response, there is a CreatedOn Date: { "CreatedOn" : "/Date(1406192939581)/" } I am looking to convert the CreatedOn date to a simple date format and then calculate the difference in days between the CreatedOn Date and the Present Date. How ...

What might be causing the JSON document to remain partially unused?

I'm experimenting with fetching JSON data from an external source for practice. I've set up all the code, but I keep encountering an error stating that the document is not fully consumed. Despite watching tutorials and reading guides, I can' ...

Steps to Identifying Discrepancies in JSON Documents and Displaying the Line Number of Each Variation

I need to compare two JSON files that have the same order of objects. My goal is to identify and print out any differences between them, along with the line number where each difference occurs. For instance, The desired output is: "Discrepancy detected in ...

Decoding with Gson: Say No to Wrapper Classes

Working on deserializing the JSON data provided using Gson in Kotlin. { "things": [ { "name": "Thing1" }, { "name": "Thing2" } } } Currently, there are two classes involved in deserialization; ThingWrapper - Contains a p ...

Improving the efficiency of JSON web services through Retrofit optimization

Currently, I am using Retrofit and have implemented the ItemTypeAdapterFactory class which implements TypeAdapterFactory and handles the read method. Everything is functioning perfectly, but I have noticed a significant slowdown when dealing with a large a ...

Getting a string array from a JSON object within the deserialize method

I am working with a JSON object that looks like this: { "name": "John", "age": 29, "bestFriends": [ "Stan", "Nick", "Alex" ] } In my code, I have created a custom implementation of JsonDeserializer: public class CustomDeserializer im ...

Parsing JSON responses for either arrays or objects

Struggling with a design issue using Gson as my parsing library while creating a library to consume a Json API. One of the endpoints returns an array of objects under normal circumstances: [ { "name": "John", "age" : 21 }, { "name": "Sar ...

Steps to generate a POJO class with a dynamic key

Is there a way to generate a pojo class based on the responses from the same URL provided below? RESPONSE 1: { "info": { "price": 1, "map": { "1": 1, "2": 2, ...

GSON is able to convert JSON data into an array even if the original source is

My aim is to deserialize this data using GSON into a list of Post objects. The challenge I'm facing is how to instruct GSON to ignore the root element "posts" (since it's an object) and focus only on processing the array. This is what I currently have: T ...

Converting XML attributes to JSON using Java

Having a bit of trouble converting an XML file with attributes to JSON. Specifically, there is an issue with the BvdState attribute that is causing the conversion to fail. Not quite sure what steps to take in order to resolve this issue. <State> ...

Encountered an issue with JSON parsing: Expected an array but received a string at line 1, column 1 while transferring data from PHP

I am facing an issue with my code. I need to extract values from a PHP script that encodes a JSON array; My PHP code : <?php $roro = array(); $roro[] = array( 'id' => '1', 'title' => 'title1' ...

Utilizing Gson to deserialize a list of Java objects containing new elements with missing IDs

Within my tree structure consisting of ol and li elements, I am dynamically adding new elements. However, when attempting to deserialize them into a Java object, an error occurs: SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/ ...

I'm encountering a persistent issue of receiving null when attempting to read a JSON object file in

Every time I attempt to read, the result is always null. This pertains to a json file. { "team": { "name": "john 1", "id": "12345" } } I am attempting to accomplish this using POJO. public class Team { private String name; private ...

Unraveling a specific typed object from JSON in Java after it has been serialized as an Object - Here's how!

I'm just starting out with Java! My objective: I am looking to create a collection of Objects that allows me to store objects of any type using a key (similar to a Map). I should be able to add objects of various types to this collection, such as an ...

How to use Gson to deserialize JSON in Java

Struggling with deserializing json in java using gson. This is the json I am working with: {"races":[ {"id":1,"mask":1,"side":"alliance","name":"Human"}, {"id":2,"mask":2,"side":"horde","name":"Orc"}, {"id":3,"mask":4,"side":"alliance","name":"Dwarf"}]} ...

Learn how to extract a specific field from a String containing JSON data using Gson or another Java library

I have a String that contains JSON formatted information, specifically an OAuth token. How can I extract the refresh_token? This is the JSON data printed from the inputLine: { { "access_token":"ffa6ea48612b19966383fd6b134fe2c4daac80ce31a8632284b ...

How to initialize an enum in Java using Gson

Take a look at this piece of code: public class MyClass { public static enum MyEnum { ENUM_A("This is option A"), ENUM_B("This is option B"); private String description; private MyEnum(String desc) { this.description = desc; } ...

Using @GET parameters with Android's retrofit

I have created an interface to fetch weather data from the OpenWeather API for the city of RZESZOW in the country POLAND. How can I pass query parameters for the user to input their desired city name and country in order to get the weather data? public in ...

Transform JSON data into a custom Vaadin Charts theme using GSON

Upon examining the JSON data serialized from a Vaadin Charts default theme, here are some key elements: { "colors":[ { "color":"#2f7ed8" }, { "color":"#0d233a" }, { "color":"#8bbc21" }, { "color":" ...

Working with JSON parsing in Gson or Jackson when a field can have two distinct types

My JSON data includes a field that contains two different types. "fields":[{"value":"ZIELONE OKO"},{"value":{"@nil":"true"}}] I am struggling with deserializing these values. The model class I am using has the following structure: private String value; ...

gson: customized fromJson method based on the data type

Apologies if this has been asked before, but I couldn't find the information I'm looking for. Here are the different message types I have: class AbstractMessage { int code; String token; } class ShareMessage extends AbstractMessage{ ...

Having trouble extracting a boolean value from a JsonObject during the JSON parsing process

Struggling with figuring out some basic Java tasks... I have a request going to an API, and it returns the following JSON. {"success": false, "message": "some string", "data": []} The String result represents this as shown below: JsonObject root = new ...

Tips for extracting data from a nested JSON object while utilizing GSON library on Android

Here is an example of how my JSON response appears: [{"order":-1,"artist":[{"name":"Hey"}]},...] I am seeking guidance on how to extract the name from the artist object using GSON. Initially, I attempted to achieve this task utilizing the following code ...

Utilizing Json and Gson for Android Development

Could someone please explain the distinction between JSON and GSON to me? I keep coming across the term GSON while researching JSON, but I'm not sure how they differ. I'm confused about the specific differences between the two. Additionally, I've encount ...

GSON - Decoding JSON Obtained through Wikipedia API with Dynamic Object Naming

{ "batchcomplete": "uniqueText123", "continue": { "grncontinue": "0.262157292819|0.262157407383|17998004|0", "continue": "grncontinue||" }, "query": { "pages": { "54321098": { "pageid": 54321098, "ns": 1, ...