FAQ Database Discussion Community


Parse nested json data into string

java,arrays,json,parsing,gson
Context: I'm working on a middle-man service that acts like a CMS system. I get a full complex json file dropped on my server which I then need to serve out to my clients that expect json content. (let's ignore the validation part for now) I have a name, version...

Writing a serializer for Gson using Java 8

java,json,serialization,gson,java-8
I have a own class called MyDate and want to write a serializer of it for Gson. This code works: GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(MyDate.class, new JsonSerializer<MyDate>() { @Override public JsonElement serialize(MyDate date, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(date.toString()); } }); However I want to use the...

Custom deserializer or different class design Retrofit

java,android,gson,deserialization,retrofit
Retrofit makes things so easy for a noob like me. However, the API response structure that I'm requesting for my current project doesn't follow the same format as I have used before. I am unsure of whether I need to rewrite my POJO or make a custom deserializer in GSON....

Android JSON cant deserialize ArrayList out of START_OBJECT (JSON WITH BAD STRUCTURE)

java,android,json,jackson,gson
Hi guys i'am with a problem with some bad JSON structure from my client server, my client can't change and i have handle in this side. I'am creating POJO from JSON and I've already tried with GSON and now i'am using JACKSON because i thought the JACKSON TREE will help...

deserializing a JSON file with GSON

java,android,json,gson
I develop an Android application and I have to deserialize a JSON file. I have these classes: public class Medicine { @SerializedName("substanta_activa") private List<String> active_substance; @SerializedName("produse") private List<Product> product; @SerializedName("dozaj") private Dosage dosage; @SerializedName("mentiuni") private List<String> notes; @SerializedName("cuvinte_cheie") private List<String> keyword; /* + getters and setters */ } public class...

MusixMatch API and GSON: Using track.snippet.get instead of track.lyrics.get

java,json,gson,deserialization
I am working on the final project for an intro to Java class. Part of the project involves getting a lyric snippet from MusixMatch using their API. I am able to get lyrics from the API using track.lyrics.get, but cannot get snippets using tracks.snippet.get. I started with a Java wrapper...

JSON has unique keys for all objects, how to convert to POJO using GSON? [duplicate]

java,json,gson
This question already has an answer here: Dealing with randomly generated and inconsistent JSON field/key names using GSON 2 answers I have a particular situation where I am retrieving a list of Objects which have unique Ids as their keys, and they also have nested objects which also have...

Reading value of nested key in JSON with Java (Jackson)

java,json,jackson,gson
I'm a new Java programmer coming from a background in Python. I have weather data that's being collected/returned as a JSON with nested keys in it, and I don't understand how pull the values out in this situation. I'm sure this question has been asked before, but I swear I've...

How can I deserialize this json string with gson?

android,json,gson
I am trying to deserialize this JSON string in an Android project but I have no experience in it whatsoever. {"nodes":[{"node":{"title":"esesese", "body":"hey world whatup"}}, {"node":{"title":"Asdasd", "body":"asdefasdefe"}}]} I was trying to do something like this, but it won't work: public class Nodes { public Node[] nodes; } public class Node {...

Not able to frame correct JSON String

json,gson
I am learning JSON and using gson to frame json string. Here it is what i need. { "version": "1.0", "interface_type": "web", "request_type": "1", "username": "test", "password": "test", "sender_id": "test", "doctor_advice": false, "type": "test", "bulk": "test", "msg": "test", "recipients": [ 919845098450, 919845098451 ] } But i am getting like this....

Base64 encode single row in an array

php,android,base64,gson
I'm building an Android app, that is supposed to be able to take a photo, and then store it in a database. I got that part down. However when I try to load it into my app again, that's when it gets tricky. I have the image stored as a...

Adapting Retrofit responses using GSON

android,json,gson,retrofit
I would like to agnostically retrieve the child element of a known JSON object with every successful response I receive from a particular API. Each server response returns the following JSON format (condensed for simplicity): { "status": "success", "error_title": "", "error_message": "", "data": { "messages": [ { "message_id": "123", "content":...

How to get the response data from cloud to string

java,json,gson,google-cloud-storage,restlet
I want to get the response to a string variable from the data from the cloud. ClientResource cr = new ClientResource("http://localhost:8888/users"); cr.setRequestEntityBuffering(true); try { try { cr.get(MediaType.APPLICATION_JSON).write(System.out); } catch (IOException e) { e.printStackTrace(); } } catch (ResourceException e) { // TODO Auto-generated catch block e.printStackTrace(); } I have response as...

Gson: Not a JSON Object

java,json,gson
I have the following String passed to server: { "productId": "", "sellPrice": "", "buyPrice": "", "quantity": "", "bodies": [ { "productId": "1", "sellPrice": "5", "buyPrice": "2", "quantity": "5" }, { "productId": "2", "sellPrice": "3", "buyPrice": "1", "quantity": "1" } ] } which is a valid json for http://jsonlint.com/ I want...

How to parse with GSON when identifier has space in name and Turkish Char [closed]

java,gson
How can i parse this json with GSON to my model? Thanks for help. { "Kod":"XU100", "Son Değer":"83.947", "En Düşük":"83.947", "En Yüksek":"86.355" },...

Read nested json objects that have been serialized via gson library

java,json,serialization,gson,deserialization
I am storing an object in shared preferences. To do this I am serializing the object using the gson library and a typeadapter before storing them. Here's what my object looks like in json: { "id": 0, "name": "Sensor 2D:D3:5C", "address": "00:07:80:2D:D3:5C", "device": { "mAddress": "00:07:80:2D:D3:5C" }, "temp": "31342e37" }...

In Gson, how can I deserialize a Map of Lists of arbitrary classes?

java,json,gson
I have an API that returns data as follows: { gene: [ ], attribute: [ ], dataset: [ ] } Each List contains an object that should be deserialized to a specific class. For example, each JSON object in the dataset list should be deserialized to a Dataset class. I...

JsonSyntaxException : Expected a String but was NAME

android,json,gson,retrofit
I'm having some problems with parsing JSON from a 3rd party. "field_head_picture":{ "und":[ { "fid":"11917", "uid":"1", "filename":"fr_bril_id_promo.jpg", "uri":"public://fr_bril_id_promo.jpg", "filemime":"image/jpeg", "filesize":"12744", "status":"1", "timestamp":"1429724219", "uuid":"bb8c1a73-451c-4e17-9001-146c6e06f255", "display":"1", "description":"" } ] } and sometimes it returns "field_head_picture":[ ], As you can see it returns an object or an empty array. I know this is...

Fields not deserialized when instance creator is registered with gson

java,json,gson
I'm using gson to deserialize objects, and I'm telling gson the interface class rather than the implementation class of the object I want. I register an InstanceCreator that constructs an instance of the implementation class. This test demonstrates the problem that I encounter: public class UnexpectedGsonBehaviorTest { public static interface...

Google Map Direction Api using Retrofit

android,gson,google-maps-android-api-2,retrofit
I want to draw the route between two Location. I used the retrofit library to call the API. I didn't get any response. I need the polyline in an ArrayList. How i do that? Need help to create the GsonAdapter also... Thank you..

How can I deserialize JSON to Java Object using GSON when the JSON using dates as property names?

java,gson
I have a JSON response that I want to deserialize using GSON. The JSON structure uses date strings as property names. How would one go about deserializing such. { 2015-04-23: [{ seqNum: 1, distance: 13, start: "123 Main St" end: "225 Broadway" }, {seqNum: 2 distance: 21, start: "225 Broadway"...

Dynamically tags parsing Json Data using gson

android,json,gson
I have a JSoN data like this: { "data": { "noofCity": "1", "City 1": [ { "id": "12", "title": "Delhi" } ] }, "success": true } Now based on noofCity next tag City 1 will be generated. If noofCity will be 2 then there are two tag City 1 and...

Gson not deserializing JSON data

java,json,serialization,gson
I am trying to get some weather information from Yahoo APIs. This is my JSON: JSON This is my DTO: public class forecast implements Serializable { private static final long serialVersionUID = -520652416977871134L; private String text; private String high; private String day; private String code; private String low; private String...

Is it possible to have a Gson constructor that runs after the attributes get their value?

java,gson
Is it somehow possible to enable / write a constructor for a class that would run after that class' attributes receive their value from Gson.fromJson() method? So that I can calculate some attributes value that derive from the ones that have been deserialized? For example: ps: For some reason my...

How to can I parse this json?

java,json,gson
I am trying to parse the Json result returned from this url. I want to get title, content and thumbnail value. I tried to make a java class to Map those values . import java.util.List; public class Dbpediaresults { private Results results; public Results getResults() { return results; } public...

Parsing json [Twitter streaming API 1.1]

json,gson
Im able to read a json response from the Twitter streaming api and this is a single message (tweet) that i have to parse: JSON { "created_at":"Thu Apr 30 10:47:49 +0000 2015", "id":593728455901990912, "id_str":"593728455901990912", "text":"RT @yeahsjustin: when ur bieber af http:\/\/t.co\/dI7f9u6zNH", "source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e", "truncated":false, "in_reply_to_status_id":null, "in_reply_to_status_id_str":null, "in_reply_to_user_id":null,...

Creating GSON object error

java,servlets,gson
I'm trying to create Gson object inside Java Servlet class. public class SendNews extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Before creating"); Gson gsonObj = new Gson(); System.out.println("This line and the whole code below will be skipped."); System.out.println("And this method will be finished...

how to parse JSON file with GSON

java,json,gson
I have a very simple JSON with reviews for products, like: { "reviewerID": "A2XVJBSRI3SWDI", "asin": "0000031887", "reviewerName": "abigail", "helpful": [0, 0], "unixReviewTime": 1383523200, "reviewText": "Perfect red tutu for the price. ", "overall": 5.0, "reviewTime": "11 4, 2013", "summary": "Nice tutu" } { "reviewerID": "A2G0LNLN79Q6HR", "asin": "0000031887", "reviewerName": "aj_18 \"Aj_18\"", "helpful":...

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

android,json,gson
I'm getting a Json response from Flickr api which is like : { "photos": { "page": 1, "pages": 1, "perpage": 100, "total": 2, "photo": [ { "id": "14774811932", "owner": "[email protected]", "secret": "cbb99f0039", "server": "3853", "farm": 4, "title": "Weltschmerz", "ispublic": 1, "isfriend": 0, "isfamily": 0, "date_faved": "1432471819" }, { "id": "13274800365",...

Gson Exception Expecting object found

java,gson,android-gcm
I am using the gSON API 1.7.1 sometimes having following error. Is there a bug for this version? Do I need to upgrade the current version 2.x.x com.google.gson.JsonParseException: Expecting object found: "<!DOCTYPE" at com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler(JsonObjectDeserializationVisitor.java:100) at com.google.gson.ReflectingFieldNavigator.visitFieldsReflectively(ReflectingFieldNavigator.java:63) at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:120) at...

Gson: java.util.Map convert all key-value pairs

java,json,gson
I have following code: Collection<Product> products = productRepository.findProducts(from, pageSize); Map<Product, BigDecimal> map = new TreeMap<>(new ProductComparator()); for (Product product : products) { BigDecimal buyPrice = warehouseView.find(product.getId()) .getBuyPrice(); map.put(product, buyPrice); } Gson gson = new Gson(); String json = gson.toJson(map); String json2 = gson.toJson(map, new TypeToken<Map<Product, BigDecimal>>(){}.getType()); JsonElement json3 = gson.toJsonTree(map,...

Parsing JSON with google-gson

java,json,gson
From the server comes the answer { "error":false, "lessons":[ { "id":1, "discipline":"??????????", "type":"LECTURE", "comment":"no comments" }, { "id":2, "discipline":"???. ??", "type":"LECTURE", "comment":"no comments" } ] } How correctly read object "lessons", and add to List ?...

InputStream to JsonObject - GSON

java,android,gson
I've a lot of trouble converting a result from this api to a JsonObject. The "result" stays null no matter what I try to do. URL url = new URL(urlString); InputStream input = url.openStream(); Reader reader = new InputStreamReader(in, "UTF-8"); JsonResult result = new Gson().fromJson(reader, JsonResult.class); JsonResult class public class...

Assistance with JSON from URL

java,json,gson
I am trying to fetch JSON from a URL in Java, and output results. Here is my json, from www.thebluealliance.com/api/v2/match/2015arc_qm1. I want to get the match_number, and the scores from the blue and red alliances, and print it to my console. I am using GSON (Google JSON). For example, I...

GSON - Deserialize primitive array

java,json,gson,deserialization
Consider this simple Json: { "test": [ 0, 3 ] } Now I want to deserialize it in a simple int array so for that I use a custom deserializer: class ArrayDeserializer implements JsonDeserializer<int[]> { @Override public int[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return context.deserialize(json.getAsJsonObject().getAsJsonArray("test"), int[].class);...

Java parse “\n” as not line break

java,json,gson
I am parsing a json file using gson. Each line in the json file is one JSON object. In one of the fields, there is a bunch of unicode, coupled with \n {"id":"12345", "text":"RT @abo_khalid_03: \u0644\u0623\u0646 \u0623\u0645\u0631\u0643\u0650 \u064a\u0647\u0645\u0646\u064a\ud83c\udf39\n\n\u0635\u0648\u0631 \u0627\u0644\u0646\u0633\u064e\u0627\u0621 \u0641\u064a \u0627\u0644\u0639\u0631\u0636 \u0627\u0645\u0627\u0645 \u0627\u0644\u062c\u0645\u064a\u0639 \u0625\u062d\u062f\u064e\u0649 \u0627\u0644\u0630\u0646\u0648\u0628...

GSON: fromJson(Reader json, Type typeOfT) vs fromJson(String json, Type typeOfT)

java,android,json,gson
I'm working with a code base that takes the body of a network response and feeds it to a GSON instance with fromJson(Reader json, Type typeOfT) to create POJOs. Usually I'll see a call to fromJson(String json, Type typeOfT) but they're adamant that using the Reader call is better. What's...

Android: Indeterminate progress bar for ServerCall routine.

android,json,gson,android-progressbar
I'm working on a simple I.M android app for class that makes queries to a server and displays the results (i.e messages) on a ListView. One of the requirements is that the app display an indefinite progress bar while the query is being made. This means that I have to...

Android JSON parsing using Volley

android,json,gson,android-volley
Ok so an answer to my question suggested for Volley implementation. I did try some examples, read some articles and yeah I'm kinda excited about Volley, it can make my apps life easier. but there is not a lot of documentation out there and for I newbie like me, I...

Parse JSON String without array name with GSON

java,android,json,gson
I am getting a JSON String {"status":208,"routes":[1,9,3]} from a Jersey project in my Android app. The JSON String has no flag name for it. Is it possibale to parse it with GSON libarary ? I am just actually intressted just in the ArrayList routes values in it. I have done...

Retrofit Query is not working properly?

android,json,rest,gson,retrofit
i want to fetch the json details from the sever.when i query, it's not working.when i hard code the url it is working.. CASE 1 @GET("/quiz/create_json/sub_cat.php?main_cat_id=") void showSubCategory1(@Query("id") int id,Callback<Object> callback); retrofitService.showSubCategory1(id, new Callback<Object>() { @Override public void failure(RetrofitError error) { Log.d(TAG, "Failure"); } @Override public void success(Object list, Response...

Valid JSON still getting parse error

java,android,json,gson
My JSON is: [ { "name": "Gears Live Wallpaper", "url": "market://details?id=com.appbasic.gearslivewallpaper", "image": "http://appbasic.com/promimg/gearslivewallpaper.png" }, { "name": "Phone hanging too much ?", "url": "market://details?id=com.indiaapps.speedmaster", "image": "http://appbasic.com/promimg/speedmaster1.png" }, { "name": "Rainbow Photo Frames", "url": "market://details?id=com.appbasic.rainbowphotoframes", "image": "http://appbasic.com/promimg/rainbowphotoframes.png" }, { "name": "Military Photo Suit", "url":...

JSON Nested Objects

java,json,gson
I'm working with a JSON file that has nested objects like this, { "LocId":99, "typeId":99, "name":"foo", "parentId":99, "geoCode": { "type":"bang", "coordinates": [{ "latitude":99.0, "longitude":99.0 }] } } I created a container to hold the JSON file in a class like this, public class Location_JSON { private LocId id; // +getter+setter...

Simple JSON parsing using GSON throwing IllegalArgumentException

android,json,wordpress,gson
What I want is this: 1)send a GET request to a Wordpress site 2) Get the json response from the site 3) from that response (which I cannot know how or what elements it contains but I know for sure it contains at least one that interests me. That being...

How to parse this JSON String with GSON?

java,json,gson
Can't figure out how to parse the following JSON string with GSON into any proper object to retrieve its data. The string is: {"Values":[{"Date":"2014-10-01","Value":386788.0},{"Date":"2014-11-01","Value":429131.0},{"Date":"2014-12-01","Value":215217.0},{"Date":"2015-01-01","Value":270422.0},{"Date":"2015-02-01","Value":261412.0},{"Date":"2015-03-01","Value":354668.0}]} I figured out that square brackets mean that it's an ArrayList, but then there's another object inside. If I try and try to iterare over the...

Cannot convert json file to list of objects using gson API caused by an illegal attribute's name

java,json,gson
Consider this json file example.json [ { "permalink": "c8635076fa371e7642e6e284cc9b60dc", "pecas": { "1401 Pecas Midia Grafica_v2/Whirlpool_LinhaBranca_Positivo_CanaisdeAfinidade_SuperBanner_-": { "id": "6a082df27f9fe4be184d7222b79c2f8a", "path": "p-554ba68ce4b04befa5148ae4/conteudo/08039a5f3ea1924ed7950bc0caf434a2.swf", "nome": "Whirlpool_LinhaBranca_Positivo_CanaisdeAfinidade_SuperBanner_-.swf", "pathOriginal": "1401 Pecas Midia Grafica_v2/Whirlpool_LinhaBranca_Positivo_CanaisdeAfinidade_SuperBanner_-.swf", "imagem":...

How do I use custom deserialization on gson for generic type?

android,json,gson
For standard POJO, we can use the following GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(MyType2.class, new MyTypeAdapter()); gson.registerTypeAdapter(MyType.class, new MySerializer()); gson.registerTypeAdapter(MyType.class, new MyDeserializer()); gson.registerTypeAdapter(MyType.class, new MyInstanceCreator()); How about if the POJO is generic? gson user guide (https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization) doesn't mention it. Below is my code but it's not the correct one....

GSON Parsing error

android,gson
This is my json, {"status":"success","data":{"name":"Test","mob_no":"8089647076","country_prefix":"+91","email":""}} please note that "email":"" when i try to parse this using gson its throwing error 03-16 16:50:29.019: E/AndroidRuntime(11039): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gsonsample/com.example.gsonsample.MainActivity}: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unexpected value at line 1 column 11 My model class public class APIBase { String status;...

parsing of JSON with GSON on Android

java,android,json,arraylist,gson
I've successfully parsed http://kylewbanks.com/rest/posts this data into my Android application. This JSON takes the format of [ {...}, {...}, {...} ] My issue is that I need to parse JSON in the format of { "count":3, "result":[ {...}, {...}, {...} ] } I'm aware that I need to get past...

populate a hashmap with json data from file

java,json,hashmap,gson
I want to represent this file in my java program. What I want to do is quickly search through it by "key" value, so for instance, given the value P26 I'd want to return spouse. I thought I could do it in this way: BufferedReader reader = new BufferedReader(new FileReader(new...

Retrofit: Expected BEGIN_OBJECT but was BEGIN_ARRAY

android,json,gson,retrofit
Sorry for one more question about this error, but everything that I've read was helpless for me. I'm using Retrofit Library and GSON for parse JSON answers. I got this error: E/RETROFIT ERROR﹕ com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ JSON answer: [...

Prevent GSON from serializing JSON string

java,json,serialization,gson
I'm new to gson, and have newby question which I have not found an answer to, so please bear with me. StackOverflow and google were not my friend :( I have a java class "User", and one of its properties, "externalProfile" is a Java String containing already serialized JSON. When...

Custom Converter for Retrofit

android,json,parsing,gson,retrofit
I am trying to use a custom converter for Retrofit RestAdapter.Builder builder = new RestAdapter.Builder() .setEndpoint(BuildConfig.BASE_SERVER_ENDPOINT) .setClient(new OkClient(client)).setConverter(new CitationResponseConverter()) .setLogLevel(RestAdapter.LogLevel.FULL); below is my custom converter public class CitationResponseConverter implements Converter { @Override public Object fromBody(TypedInput typedInput, Type type) throws ConversionException { try { InputStream in = typedInput.in(); // convert the...

Error when passing facebook value: gson.JsonPrimitive can not be cast to gson.JsonObject

java,android,facebook,gson
I got this error when I parsed the Facebook Json from my Login.java to other activity: java.lang.ClassCastException: com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject When trying to do this: (AnotherActivity.java) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.profile); callbackManager = CallbackManager.Factory.create(); String token; token = getIntent().getExtras().getString("token"); pref.getPref(PREF_IS_LOGIN); System.out.println("pref : "...

Using Gson to serialize strings with \n in them

java,serialization,gson
\n in a string is effective in printing the text following \n in next line. However, if the same string is serialized using Gson, then \n is no more effective in printing it in next line. How can we fix this ? Sample program given below. In the program below,...

Parsing complex nested JSON data with Gson

java,json,object,nested,gson
I'm using Gson to parse a JSON string. I want to convert this to an object using a container class and embedded static classes. To some extent this has been possible, but I want to treat the content of stuff1 and stuff2 as arrays, for example, stuff1 is an array...

How does Gson TypeToken work?

java,generics,gson,erasure
I understand that in Java contrary to, for example, C# generics are compile-time feature and is removed via type erasure. So, how does Gson's TypeToken really work? How does it get the generic type of an object?

Deserializing objects with gson, Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

java,android,json,gson
i'm working on deserialization of feed coming from server. I have encountered a weird issue with Gson library. I'm using code i've found here on stack on similar issue thread, but it doesn't work. Class: package com.lanceit.haito.lanceit.model; /*t*/ import java.sql.Timestamp; import java.util.ArrayList; public class FeedItem { private String username; private...

Joda DateTime Json date format issue

json,datetime,gson,jodatime,jsonobject
I would like the JSON output to be in a particular date format. My JSON output is: "data":[[{"id":1,"createTimestamp":{"iMillis":1431463708237,"iChronology":{"iBase":{"iMinDaysInFirstWeek":4}}},"startTimestamp":{"iMillis":1420092000000,"iChronology":{"iBase":{"iMinDaysInFirstWeek":4}}},"endTimestamp":{"iMillis":1451541600000,"iChronology":{"iBase":{"iMinDaysInFirstWeek":4}}}}]] But I would like the timestamps to be in this format: 2015-05-12T20:48:28.237Z My code: JSONArray a = new JSONArray(); a.add(aList); JSONObject j = new...

Deserialize array of objects inside another object using Gson

java,android,json,gson,json-deserialization
Using volley in my android project I am getting json response like: { "value1": 1, "value2": aaa, "subvalues": [ { "value1": 297, "value2": 310, "calss3": { "name": "name1", "id": 1, "value": 32 } }, ... ] } I need to deserialize it to pojo using Gson. Classes are: class1: public...

How can I deserialize a JSON object but keep a specific field as a String instead of a nested object?

android,json,gson
I have a json structure which I've pasted below. I'd like to deserialize the json into a java POJO using Gson which is pretty straight-forward, except that I want to keep one of the fields, data, as a String type instead of a nested object. JSON structure { "created_on": "2015-06-04T16:12:04-0700",...

Parse nested Json with GSON

java,android,json,gson
I have a JSONArray and inside that, there are many JSONObjects. A sample of the object is: { "geometry": { "type": "Point", "coordinates": [ 11.245292261254553, 43.77014284210037 ] }, "type": "Feature", "properties": { "nome": "Biblio", "type": "bibl", "email": "[email protected]", "note": "", "indirizzo": "ERINI", "numero": "19" }, "id": 1 }, All these...

Collapsing nested structures in Gson deserialization

android,json,gson
So I'm building an API client for a service that uses a lot of deeply nested objects/arrays in the json response. For example: "foo":{ "name":"something", "id":1 "data":{ "items":[ ... //item objects ... ] } } And I'd like my parsed "foo" class to skip the "data" member and look something...

GSON: Not creating correctly using my JSONEntity only in published app, using Android Studio it works fine

android,gson
My problem is happening only on published apk. The app installed through Android Studio works without any error. But the installed through Google Play is generating my JSON file using GSON library incorrectly, seem that it is not using my JSONEntity on published apk. Correct: Generated file on my app...

Using Gson to convert Json into Java Object

java,json,class,gson
I am currently working on a project where I am using the Steam Web API. The API returns data in JSON format and I wanted to make a Java program that uses this data. Here is the following JSON format from the API: { "response": { "players": [ { "steamid":...

How to parse JsonObject to List using gson

android,gson,android-volley
I need a list of objects and I'm having problems to get it. I'm pretty new using this so someone who can help me? I'm using volley to get a jsonObject and then I need convert it(I saw the best wa to do this is with gson). Below you can...

Deserialize json array and extract value using rest assured

json,gson,rest-assured
I am a java, json, rest assured newbie and trying to work and learn how to test a rest api. I have an array returned as a rest assured response: Response response = given(getProjectInfoRequest).get(); response.asString(); { "options": [ { "text": "111", "label": "ABC" }, { "text": "222", "label": "DEF" },...

The constructor JsonPrimitive(Object) is not visible

java,android,json,gson
I am trying to wrapp an arrayList as Json string to send it to the Server with the Gson library but I am getting this error The constructor JsonPrimitive(Object) is not visible. How can I fix that? I appreciate any help. SelectedRoute class: public class SelectedRoute { ArrayList<Integer> selected; public...

Spring JSON serialization, Gson deserialization

java,json,spring,serialization,gson
I'm currently having an issue with the deserialization of certain inner-objects, in spring, I initialize all of my objects before outputting them using @ResponseBody. As an example, this is a response: [{id:1, location:{id:1, ... extra location data}}, {id:2, location:1} ] Now, GSON throws an error as it is not able...

Convert dbcursor object into json

java,json,mongodb,gson
I have a java application where I want to send json data fro servlet to a jsp. I am using mongodb as a database and Gson library for Json. I am new to Java & Mongo. Here is the code for querying the database: MongoClient mongoClient = new MongoClient("localhost", 27017);...

GSON custom serializer for an object with a Collection field

java,json,serialization,collections,gson
I have the following schema: public class Student { String name; List<Integer> sequence; } I need the Json of my Student object to be { name : "Bruce" sequence : { index_0 : 5 index_1 : 2 index_2 : 7 index_3 : 8 } } The documentation doesn't clearly say...

Gson parse json array of length 1 into JsonArray object instead of JsonObject object [duplicate]

java,arrays,json,gson
This question already has an answer here: Gson handle object or array 1 answer Using Gson, I am trying to force my json objects to have an array value with one element. Although I construct the json this way, the JsonParser creates a new JsonObject in place of my...

ProGuard: ClassCastException

java,gson,proguard,obfuscation
I'm getting this annoying ClassCastException when I obfuscate my Java code (which works fine before I obfuscate using ProGuard). java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to net.minecraft.launcher.profile.Profile at java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to net.minecraft.launcher.profile.Profile at net.minecraft.launcher.profile.ProfileManager.getSelectedProfile(SourceFile:117) at net.minecraft.launcher.g.run(SourceFile:184) at...

JSON Array Of Entries to POJO

java,arrays,json,gson
I have a JSON file that has multiple entries inside of an array. Each of those entries needs to be mapped to a java object. Here is the JSON string I am testing with (http://jsonlint.com/ validated the JSON below, but I had to erase all of the escape characters which...

Gson Type Adapter vs. Custom Deseralizer

java,gson
The example below shows a class (Club) that contains a collection of an abstract class (Member). I'm confused as to whether I need a TypeAdapter or JsonDeserializer to make the Deserialization work correctly. Serialization works just fine without any help, but Deserialization is throwing exceptions. To illustrate I've built the...

Ignore the Jackson JsonIdentityInfo during serialization

java,spring,serialization,jackson,gson
I'm currently using the @JsonIdentityInfo during deserialization and during serialization at some point in my application (During communication with certain clients) but some of my other clients simply can't use the @JsonIdentityInfo, is there away of ignoring it during serialization on some methods in spring? For example: [{id:5, innerobject:{id:1, name:"inner"}},...

What is the reasoning on modelling a class to represent JSON data and do I need to?

java,json,gson
I have come across this question on StackOverflow which asks about converting JSON to Java. The answer shows that another class is modelled to represent the JSON data as well as an object being created and I don't understand why. Does that object now contain all the information after Gson...

What is the GSON disableHtmlEscaping equivalent in JacksonJsonProvider

java,rest,jackson,gson,hateoas
I am trying to convert an URL e.g. https://api.test.com/cusomter?customer_id=1&customer_type=A but during serialization its getting converted into https://api.test.com/customer?customer_id\u003d1\u0026customer_type\u003dA I know that in GSON there is disableHtmlEscaping option to escape html safe conversion of = and & characters. Can you please let know the equivalaent option in JacksonJsonProvider....

Gson deserialize null pointer in released apk

android,json,debugging,gson,release
I'm writing an Android app need using gson to deserialize the json string: { "reply_code": 001, "userinfo": { "username": "002", "userip": 003 } } so I create two classes: public class ReturnData { public String reply_code; public userinfo userinfo; } public class userinfo { public String username; public String userip;...

parse json file using gson/jackson java API

java,json,jackson,gson
I am a new bee to both JSON and GSON. My JSON structure is as mentioned below and i am using gson library to parse the json object and retrieve the values I am getting all null values from the getters. Can anyone help me on this. JSON file: {...

Java Class for obtaining corresponding Gson json object

java,json,gson
I have a json object with following representation : { text : "Ed O'Kelley was the man who shot the man who shot Jesse James.", entities : [ ['T1', 'Person', [[0, 11]]], ['T2', 'Person', [[20, 23]]], ['T3', 'Person', [[37, 40]]], ['T4', 'Person', [[50, 61]]], ], }; I need to create...

Gson how to avoid Expected BEGIN_ARRAY but was BEGIN_OBJECT? [duplicate]

java,json,gson
This question already has an answer here: Parsing JSON with GSON, object sometimes contains list sometimes contains object 1 answer I am using GSON to parse JSON data into Java and I am running into the error that is stated in the title. I am working with an API...

Does retrofit interfaces support templated callbacks

gson,retrofit
I have an API the returns a standard reply for all requests that gets parsed by gson/retrofit. public class ServerReply<T> { @Expose private String status; @Expose private T data; @Expose private String message; } I have an interface for Retrofit that will return a list of users inside of serverReply....

How to convert Map of class objects to json java

java,json,gson
I have class with some properties, for example: public class MyClass { public int number; public String s; } and I want to convert Map of this class to json. for example: Map<String, MyClass> map = new HashMap(); map.put("sss", new MyClass(1, "blabla"); json j = new json(map); and I want...

Karaf / Maven - Unable to resolve: missing requirement osgi.wiring.package

java,maven,gson,apache-karaf
I am unable to start a bundle in Karaf (version 3.0.1). The bundle is built using maven and it imports gson. I included gson in maven as required: <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3.1</version> </dependency> The build goes fine. However, when deploying the bundle I receive this Warning from Karaf: 2015-05-27 12:45:07,371...

How to deserialize class containing arraylist with timestamp data

java,json,gson
I have a jsonstring as below {"coaList":[{"iD":324,"strName":"Cash","hasChildren":false,"amount":3500.0,"transDate":1421346600000},{"iD":326,"strName":"Cash","hasChildren":false,"amount":2000.0,"transDate":1421346600000},{"iD":328,"strName":"HDFC Bank","hasChildren":false,"amount":2500.0,"transDate":1421346600000}]} I need to convert this string to CoaAccountList class object.Below is the CoaAccountList class. CoaAccountList.java: public class CoaAccountList implements Serializable { private List<COAAccount> coaList;...

Gson convert from JSON to Java object

android,json,gson
(I am very new to Gson and Json so please forgive me if this is a silly question) Here is the response from my POST request: String getResponse = ({"user_id":"1","device_id":"0","user_name":"jdoe","first_name":"John","last_name":"Doe"}); After getting the response, I use the following method to put the JSON values into my Java object: FacebookUser facebookUser...

How can i get GSON to parse JSON String

java,json,parsing,gson
How can I get the GSON library to correctly convert the below JSON string to objects. I've tried for ages but it only seems to pick out the 2 "Word" objects and leave the member fields blank or null. JSON: { "words": [ { "Word": { "id": "1", "word": "submarine",...

Deserializing Generic Types from a ClassLouder class with GSON

java,json,generics,reflection,gson
I´m trying to parse a JSON file using GSON, the problem is that I´m using a Class that it was previously loaded by ClassLoader. File root = new File("./build/classes"); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() }); Class<?> loadedClass = Class.forName("events.Source", true,classLoader); // JSON --> Java "Get the actual type"...

Gson Deserialization of Mixed Object types

android,json,gson
I have a JSON: "account_representatives": [ { "Sales Person": 1307, "default_ticket_assignments": [ "" ], "Primary Account Manager": 1307, "Secondary Support-3": 1151, "Relationship Mgr": 1307, "authorized_resources": [ "" ], "Technical Account Manager": 164 } ] and I have a class whose structure is like this: public class AccountRepresentative { @SerializedName("authorized_resources") @Expose...

Iterate JSON array object

java,android,json,gson
I'm new to the whole concept of java so if the title is incorrect, please bare with me. I'm querying out and getting a json string returned, for the sake of this example I'll post an example. I'm trying to figure out how I would go about digging through the...

Store java object as json string in MySQL database?

java,mysql,gson
Performance wise, is it smart to do this? An example would be with Gson Gson gson = new Gson(); String json = gson.toJson(myObject); // store json string in sql with primary key // retrieve json string in sql with primary key I want to simplify the way i store and...

How to read JSON to a list of generic objects in java?

java,json,jackson,gson
I have to get data from a web service, I'm using Jackson but I have the same problem using Gson, I have no problem with single objects but when I receive several objects list it is not that easy for me. JSON received are like this: {"country": [ {"code":"AD","nombre":"Andorra","name":"Andorra"}, {"code":"AE","nombre":"Emiratos...

Apache storm - java.lang.NoClassDefFoundError: com/google/gson/Gson

java,maven,gson,noclassdeffounderror,storm
I'm using Apache Storm 0.9.4. I set up a 5 nodes cluster and it works fine. (Actually 5 supervisors are working as docker containers on 5 different physical nodes.) My environment is here $cat /etc/redhat-release CentOS release 6.6 (Final) $docker -v Docker version 1.4.1, build 5bc2ff8/1.4.1 $java -version java version...

How do I put generic type for Gson's TypeToken?

android,json,gson,android-volley
EDIT After experimenting for a while, I know my problem is. I can't put generic type inside TypeToken (Type type = new TypeToken<CustomResponse<T>>(){}.getType();). When I change T into POJOA, I can run my app just fine to deserialize json into POJOA, but not into POJOB and POJOC. How do I...

How to use gson to convert json which contains java's keyword? [duplicate]

java,gson
This question already has an answer here: Gson Java reserved keyword 1 answer I'm using new Gson().fromJson(jsonString, javabean.class) to convert json into java bean; But there is some key named abstract in json String ,like this: { abstract : "value" } If I want to write java bean ,...

GSON parsing of nested array

java,json,gson
Im having difficulties understanding if GSON can handle this kind of json by default or do I need to implement deserializers for every sub element. json input { "services":[ { "id": 2, "name": "Buy" }, { "id": 3, "name": "Sell" } ] "status": { "code": 0, "message": "" } }...

Make a “flat” JSON using Gson()

java,android,json,gson
I would like to make a "flat" JSON of a class. Suppose I have class like the following: public class Parcel { private double area; private int type; private Address address; } and public class Address { private String street; private int number; private int flatNumber; } Is there any...

Parse JSON using Gson (or alternative for java)

java,json,rest,gson
I've worked with Gson for quite some time but this one has me scratching my head. Here is a typical json response I am getting back from a REST call. Notice that there are several nested references that are of the same type. Any idea how I can solve this...

Retrofit returns empty object, but json seems valid

android,gson,retrofit
This is the json I get from my endpoint. I got it using proxy, so this is exactly what retrofit gets: { "id": 1, "email": "[email protected]", "name": "Jacek KwiecieŇĄ", "google_plus_id": "117434793312604634191", "facebook_id": null, "avatar_url": "https://some_url", "last_login_at": "2015-06-14T12:36:58.831Z", "created_at": "2015-06-14T12:36:58.829Z", } I create RetrofitService like this: private static final RestAdapter REST_ADAPTER...