Mined and Summarized Use Cases For API: com.google.code.gson

  1. Get different JSON representations of the same object

    None .. details

    1. @SerializedName("...")

    • See Also (17)
    1. How to parse JSON Array (Not Json Object) in Android

      This may help you. And when you get the result parse like this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class CustomerInfo {
      2. @SerializedName("customerid")
      3. public String customerid
      4. @SerializedName("picture")
      5. public String picture
      6. @SerializedName("location")
      7. public String location
      8. public CustomerInfo() {}
      9. }

      Other Reactions
      1. Result variable is your JSONArray String.
      2. Would result variable be the url i need to fetch json from or already fetched json ?
      3. result string is already fetched JSONArray string.

    2. Using Enums while parsing JSON with GSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @SerializedName("${title}")TITLE,@SerializedName("${description}")DESCRIPTION

    3. Gson for Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @SerializedName("distance_info")public DistanceInfo distance_info

    4. Json Data assign to java class

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class Response {
      2. @SerializedName("ResultData")
      3. public ResultData resultData
      4. }

    5. Json Data assign to java class

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class ResultData {
      2. @SerializedName("GridRecords")
      3. public List<GridRecord> gridRecords
      4. @SerializedName("Totalrecords")
      5. public int totalrecords
      6. }

    6. Json Data assign to java class

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class GridRecord { @SerializedName("AddedTime") public String addedTime
      2. @SerializedName("TransactId") public String transactId
      3. //other fields...}

    7. Tweak JSON or GSON?

      What's wrong is that you're ignoring the root JSON Object with a single JSON Property widgets". Try deserializing your data into this object instead . details

      Reactions - Positive 2, Negative 0, Others 0

      1. public class WidgetList {
      2. @SerializedName("widgets")
      3. private List<List<Widget>> widgets
      4. }

      Positive Reactions
      1. I had to just use new Gson().fromJson(json, WidgetList.class) and that worked fine.
      2. Nice suggestion @jsn but it actually didn't work.
      Other Reactions
      1. You can't ignore the top-level object with single property.
      2. { "items" : [ 1, 2, 3 ] } does not deserialize to List, but [ 1, 2, 3 ] does.
      3. And new Gson().fromJson(json, new TypeToken>>(){}.getType());.

    8. parse a JSON feed using GSON and get an array instead of multi params

      You can do this using a Map not an array if you do not want to define all the possible fields in a Result object. Otherwise you would need to define a Result object to use instead of that Map that had all the possible method types as fields and use the SerializedName annotation because of the non-legal Java names Option C if you really want a List is creating your own custom deserializer that is passed the parsed JSON and create an object that had a List in it instead of a Map or POJO. details

      Reactions - Positive 0, Negative 0, Others 0

      1. class Result { @SerializedName("auth.gettoken") APIMethod authGetToken
      2. @SerializedName("blog.delete_post") APIMethod blogDeletePost
      3. // etc}

    9. Convert Json to an specific Class

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @SerializedName("*")public String star

    10. Parsing JSON using Google GSON: reading values directly from child objects

      Your objects have to conserve the hierarchy of your json instructions. For your example it would be something like this Using the following call . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class Object {
      2. @SerializedName("field1")
      3. public String fieldOne
      4. @SerializedName("field2")
      5. public String fieldTwo
      6. @SerializedName("field3")
      7. public String fieldThree
      8. @SerializedName("field4")
      9. public String fieldFour
      10. }
      11. public class Name {
      12. @SerializedName("object1")
      13. public Object obj
      14. }
      15. public class GsonObj {
      16. @SerializedName("Name")
      17. public Name name
      18. }

    11. Android SDK: Parsing JSON from URL using GSON

      My JSON has the following format I want to grab the above data in a separate thread I have the following code How do I go about grabbing each img-src and URL values. Use this method to fetch your Data in an Array list This should be how you should declare your ArrayList Type class here its NewsItem Here is the WebSErvice Util Class. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.annotations.SerializedName
      2. public class NewsItem {
      3. @SerializedName("title")
      4. public String title
      5. @SerializedName("content")
      6. public String title_details
      7. @SerializedName("date")
      8. public String date
      9. @SerializedName("featured")
      10. public String imgRawUrl
      11. }

      Other Reactions
      1. I have editted the post for you, so that you can have a look at the WebServiceUtil Class.
      2. where do I get the WebServiceUtils class?
      3. where you will be using @SerializedName("img-src") and @SerializedName("URL") to fill your class variables (here the class is NewsItem).

    12. Parsing JSON array with a sub-array with GSON?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @SerializedName("image") private ImageClass image
      2. // Getter and setter

    13. JSON parsing using Gson

      Rename the field to truncate and try again. Alternatively you could annotate the objChild field with an to tell gson to use the value from the truncate field in the JSON as the value for the objChild field in your Java object. details

      Reactions - Positive 1, Negative 0, Others 0

      1. @SerializedName("truncate")

      Positive Reactions
      1. Hey Thanks a lot.
      Other Reactions
      1. ?
      2. can you help to expalin "getters and setters"??

    14. Getting data from JSON

      See here gson/6593800#6593800). Hope this helps App.java Debug.java Result.java Suggestion.java . details

      Reactions - Positive 6, Negative 0, Others 0

      1. package sg.java.play_sof_json_6596072
      2. import com.google.gson.annotations.SerializedName
      3. public class Suggestion {
      4. @SerializedName("Ranking")
      5. private String ranking
      6. @SerializedName("Score")
      7. private String score
      8. @SerializedName("Title")
      9. private String title
      10. /** * @return the ranking */
      11. public final String getRanking() {
      12. return this.ranking
      13. }
      14. /** * @param ranking the ranking to set */
      15. public final void setRanking(String ranking) {
      16. this.ranking = ranking
      17. }
      18. /** * @return the score */
      19. public final String getScore() {
      20. return this.score
      21. }
      22. /** * @param score the score to set */
      23. public final void setScore(String score) {
      24. this.score = score
      25. }
      26. /** * @return the title */
      27. public final String getTitle() {
      28. return this.title
      29. }
      30. /** * @param title the title to set */
      31. public final void setTitle(String title) {
      32. this.title = title
      33. }
      34. }

      Positive Reactions
      1. I'll upvote this.
      2. Thanks man!
      3. This worked just perfect!What does the annotation '@SerializedName' do?Thanks again!.
      4. You are welcome.
      5. Very nice!
      6. Thanks again.
      Other Reactions
      1. It's a decent answer.
      2. I have no idea why someone would down vote your and my answers.
      3. :D.
      4. It provides a mapping between the key used in the JSON string, and the attribute in your Java class that you wish to map into.

    15. Getting data from JSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package sg.java.play_sof_json_6596072
      2. import com.google.gson.annotations.SerializedName
      3. public class Result {
      4. @SerializedName("Code")
      5. private String code
      6. @SerializedName("DebugLogId")
      7. private String debugLogId
      8. @SerializedName("Message")
      9. private String messahe
      10. /** * @return the code */
      11. public final String getCode() {
      12. return this.code
      13. }
      14. /** * @param code the code to set */
      15. public final void setCode(String code) {
      16. this.code = code
      17. }
      18. /** * @return the debugLogId */
      19. public final String getDebugLogId() {
      20. return this.debugLogId
      21. }
      22. /** * @param debugLogId the debugLogId to set */
      23. public final void setDebugLogId(String debugLogId) {
      24. this.debugLogId = debugLogId
      25. }
      26. /** * @return the messahe */
      27. public final String getMessahe() {
      28. return this.messahe
      29. }
      30. /** * @param messahe the messahe to set */
      31. public final void setMessahe(String messahe) {
      32. this.messahe = messahe
      33. }
      34. }

    16. Getting data from JSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package sg.java.play_sof_json_6596072
      2. import com.google.gson.annotations.SerializedName
      3. import java.util.List
      4. public class Debug {
      5. @SerializedName("DebugLogId")
      6. private String debugLogId
      7. @SerializedName("RequestId")
      8. private String requestId
      9. @SerializedName("Result")
      10. private Result result
      11. @SerializedName("Suggestions")
      12. private List<Suggestion> suggestionList
      13. /** * @return the debugLogId */
      14. public final String getDebugLogId() {
      15. return this.debugLogId
      16. }
      17. /** * @param debugLogId the debugLogId to set */
      18. public final void setDebugLogId(String debugLogId) {
      19. this.debugLogId = debugLogId
      20. }
      21. /** * @return the requestId */
      22. public final String getRequestId() {
      23. return this.requestId
      24. }
      25. /** * @param requestId the requestId to set */
      26. public final void setRequestId(String requestId) {
      27. this.requestId = requestId
      28. }
      29. /** * @return the result */
      30. public final Result getResult() {
      31. return this.result
      32. }
      33. /** * @param result the result to set */
      34. public final void setResult(Result result) {
      35. this.result = result
      36. }
      37. /** * @return the suggestionList */
      38. public final List<Suggestion> getSuggestionList() {
      39. return this.suggestionList
      40. }
      41. /** * @param suggestionList the suggestionList to set */
      42. public final void setSuggestionList(List<Suggestion> suggestionList) {
      43. this.suggestionList = suggestionList
      44. }
      45. }

    17. Parsing JSON maps / dictionaries with Gson?

      The Egg class could certainly be defined to have a method such as public Map getKey3 return mKey3;. As far as I remember you should create separate class for each json object.Try something like this If this is not what you expected you can write your own serialize/deserialize adapter. details

      Reactions - Positive 2, Negative 0, Others 0

      1. class Key {
      2. @SerializedName("childKey1")
      3. private String mchildKey1
      4. @SerializedName("childKey2")
      5. private String mchildKey2
      6. @SerializedName("childKey3")
      7. private String mchildKey3
      8. }
      9. class Egg {
      10. @SerializedName("key1")
      11. private String mKey1
      12. @SerializedName("key2")
      13. private String mKey2
      14. @SerializedName("key3")
      15. private Key mKey3
      16. }

      Positive Reactions
      1. Note that it is not necessary to implement a custom deserializer to deserialize to a simple Map from a JSON object with name:value pairs.
      2. Thanks.
      Other Reactions
      1. I posted a relevant example in another answer to this question.
      2. I'll look into customized adapters.

  2. HTTP POST using JSON in Java

    None .. details

    1. String postUrl="www.site.com"
    2. // put in your urlGson gson= new Gson()
    3. HttpPost post = new HttpPost(postUrl)
    4. StringEntity postingString =new StringEntity(gson.toJson(pojo1))
    5. //convert your pojo to jsonpost.setEntity(postingString)
    6. post.setHeader("Content-type", "application/json")
    7. HttpResponse response = httpClient.execute(post)

  3. get JSON instance to jsp through calling AJAX

    jQuery provides a function specifically designed for getting JSON through an AJAX request it's called CODESNIPPET_JAVA5 . You'd use it something like this It's important to note that you can't do because the function is asynchronous and therefore doesn't return the JSON it returns something else see the documentation linked above). .. details

    1. <script type="text/javascript"> $(document).ready(function() { var VAR_JSON
    2. function yourFunction() { // do something with VAR_JSON here } $.getJSON('yoururl.do', function(response) { VAR_JSON = response
    3. yourFunction()
    4. })
    5. })
    6. </script>

    Positive Reactions
    1. I'm new to java so kindly help me please.
    2. thank you replying.
    Negative Reactions
    1. @user1727557 I personally use the [json-taglib]( URL_http://json - taglib.sourceforge.net/) which is a set of JSP tags for generating JSON.
    2. You'd need to add a new forward for your action in Struts that directs to a JSP to generate the JSON instead of the standard JSP for your webpage.
    Other Reactions
    1. I will give a try.
    2. in struts 1 how can I forward json object instead of jsp.

    • See Also (2)
    1. Bind complex (JSON) form data automatically

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String[] jsonData = request().body().asFormUrlEncoded().get("records")MyForm myForm = new MyForm()
      2. // Record should act as form, because each JSON string data contain this typeForm<Record> form = Form.form(Record.class)
      3. // parse the JSON string and assign iterator Iterator<JsonNode> it = Json.parse(jsonData[0]).iterator()
      4. // assign to the MyForm instancewhile (it.hasNext()) { formData.records.add(form.bind(it.next()).get())
      5. // bind the JSON and add}

    2. Java Reflection - Get all instance variable names of a class

      Jackson is a good one that is also used by Spring MVC. To answer your question you can use on a class and use to check if the field is static. details

      Reactions - Positive 0, Negative 0, Others 0

      1. java.lang.reflect.Modifier.isStatic()

  4. Converting the Database details to JSON object

    It will looks like what you want. . .. details

    1. Gson gson = new Gson()
    2. // convert java object to JSON format, // and returned as JSON formatted string String json = gson.toJson(obj)

    • See Also (75)
    1. Automatic conversion of JSON form parameter in Spring MVC 4.0

      You rarely receive json as a request parameter which is why I think you should re-think your design** but if you have no other choice you need to register a custom PropertyEditor that will take care of converting the request parameter's json value into your custom type. Registration is simple in an InitBinder annotated method in your Controller class In this particular case we don't need all the methods of the PropertyEditor interface so we can use PropertyEditorSupport which is a helpful default implementation of PropertyEditor. details

      Reactions - Positive 2, Negative 0, Others 0

      1. @InitBinderpublic void initBinder(WebDataBinder dataBinder) { dataBinder.registerCustomEditor(MyMessage.class, new PropertyEditorSupport() { Object value
      2. @Override public Object getValue() { return value
      3. } @Override public void setAsText(String text) throws IllegalArgumentException { value = new Gson().fromJson((String) text, MyMessage.class)
      4. } })
      5. }

      Positive Reactions
      1. @NickSpacek No, it is a mechanism to receive [Unbounce webhook]( URL_http://support.unbounce.com/entries/307685-how-does-the-form-webhook - work) calls.
      2. Similar kind of space (marketing).
      Other Reactions
      1. Neat.
      2. "My recommendation is to never send JSON as a request parameter".
      3. Wonder why the form parameter...
      4. Is it for Mandrill?
      5. I agree, but I am not controlling the sending side, I am just implementing a receiver for a third party webhook.
      6. I'm guessing they had a client who could only receive form parameters instead of content body.

    2. Including a top level element with Gson

      I'm using Gson 2.2.4 . Change your method like this BTW note that I changed signature prefer an interface List instead of an implementation ArrayList into your methods. details

      Reactions - Positive 3, Negative 0, Others 0

      1. public static String toJson(List<Pojo> pojos) { Gson gson = new Gson()
      2. Map m = new TreeMap()
      3. m.put("pojos", pojos)
      4. return gson.toJson(m)
      5. }

      Positive Reactions
      1. You're welcome.
      2. It works!.
      3. Thanks.

    3. Adding an existing json string with Gson

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. Object object = gson.fromJson(arbitraryJson, Object.class)
      3. Wrapper w = new Wrapper()
      4. w.content = object
      5. System.out.println(gson.toJson(w))

    4. How to make a Hirarchical Json Structure with java program

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. System.out.println(gson.toJson(container))

    5. How to parse json data using in java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class Container { private CustomClass[] classes
      2. public CustomClass[] getClasses() { return classes
      3. } public void setClasses(CustomClass[] classes) { this.classes = classes
      4. }}public class CustomClass { private String screen_refresh_interval
      5. private String station_list_last_update
      6. public String getScreen_refresh_interval() { return screen_refresh_interval
      7. } public void setScreen_refresh_interval(String screen_refresh_interval) { this.screen_refresh_interval = screen_refresh_interval
      8. } public String getStation_list_last_update() { return station_list_last_update
      9. } public void setStation_list_last_update(String station_list_last_update) { this.station_list_last_update = station_list_last_update
      10. }}Gson gson = new Gson()
      11. Container customClassCollection = gson.fromJson(jsonResult, Container.class)

    6. GSON desirialization of sometimes string and sometimes object

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package stackoverflow.questions.q19478087
      2. import com.google.gson.Gson
      3. public class Q19478087 {
      4. public class Test {
      5. public int id
      6. public Object blob
      7. @Override
      8. public String toString() {
      9. return "Test [id=" + id + ", blob=" + blob + "]"
      10. }
      11. }
      12. public static void main(String[] str) {
      13. String json1 = "{\"id\": 1, \"blob\": \"example text\"}"
      14. String json2 = "{\"id\": 2, \"blob\": {\"to\": 1234, \"from\": 4321, \"name\": \"My_Name\"}}"
      15. Gson g = new Gson()
      16. Test test1 = g.fromJson(json1, Test.class)
      17. System.out.println("Test 1: " + test1)
      18. Test test2 = g.fromJson(json2, Test.class)
      19. System.out.println("Test 2: " + test2)
      20. }
      21. }

    7. GSON: Cannot correctly parse JSON object

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package stackoverflow.questions.q19228349
      2. import com.google.gson.Gson
      3. public class Q19228349 {
      4. public static void main(String[] args) {
      5. String json =
      6. "{\"key1\":\"someValue\","
      7. + "\"key2\":{ "
      8. + " \"anotherKey1\":\"212586425\","
      9. + " \"anotherKey2\":\"Martin\""
      10. + " }"
      11. + " }"
      12. String json2 = "{\"key1\":\"someValue\"," + "\"key2\":\"aString\"" + " }"
      13. Gson g = new Gson()
      14. Data d = g.fromJson(json, Data.class)
      15. System.out.println("First: " + d)
      16. Data d2 = g.fromJson(json2, Data.class)
      17. System.out.println("Second: " + d2)
      18. }
      19. }

    8. In JDK 8, is there any planned interoperability between Nashorn and the new JSON-P (javax.json) API?

      For example here is you can use Jackson or google gson mappers in javascript code. Could you elaborate what type of interoperability are you talking about?Currently API of JSON-P is very low level. details

      Reactions - Positive 1, Negative 0, Others 0

      1. var json = {}
      2. // google gson mappervar MAPPER = new com.google.gson.Gson()
      3. /** * Converts object to a json string. * @param object - the object to convert. * @return {String} the resultant json. */json.toJson = function (object) { return MAPPER.toJson(object)
      4. }
      5. json.roundtripJson = function (object) { return JSON.parse(json.toJson(object))
      6. }

      Positive Reactions
      1. Thanks for the answer, I added to my question to address your comments.

    9. How to parse JSON Array (Not Json Object) in Android

      Create a class to hold the objects. Then deserialize as follows Reference Article . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. Person[] person = gson.fromJson(input, Person[].class)
      3. //input is your String

      Other Reactions
      1. @Stebra, Exactly, I included that as a comment in the code.
      2. I asume this "input" would be URL to that json?or is it something else?

    10. Parsing Json using GSON but List is always empty

      Is some thing wrong with my alldeals class . To solve your parsing problem without changing the initial JSON string I added a class like this So that parsing is invoked like this and give you this result I added a toString method If you want to avoid the Container class you should change your JSON string removing "d" at the very beginning and at the end. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package stackoverflow.questions.q18930222
      2. import com.google.gson.Gson
      3. public class Q18930222 {
      4. /** * @param args */
      5. public static void main(String[] args) {
      6. String jsonString =
      7. "{\"d\":{\"__type\":\"DealMeDataContract\",\"DealMe\":[{\"__type\":\"DealMe\",\"Address\":\"2075 n power line rd suit 1\",\"CategoryId\":\"1\",\"CategoryName\":\"Personal\",\"City\":\"pompano beach\",\"CreatedDate\":\"\\/Date(1377621018533+0000)\\/\",\"DealMeId\":\"5b9b00d9-e8bf-4197-bd2a-36bc5872359f\",\"Description\":\" Get 2 Kick-it Kits now for the price of one. Only $19.99\\u000d\\u000aYou welse!\",\"ExpiryDate\":\"\\/Date(1383263940000+0000)\\/\",\"HasAgreedTermsAndConditions\":true,\"ImageUrl\":\"null\",\"IsNewAddress\":false,\"LastUpdatedDate\":\"\\/Date(1377621018533+0000)\\/\",\"Latitude\":26.24161,\"Longitude\":-80.1f909,\"PhoneNumber\":\"(954)-454-88\",\"PreviousDealAddress\":\"2075 ne rd suit 1\",\"PreviousDealCity\":\"pompano beach\",\"PreviousDealState\":\"FL\",\"PreviousDealZipCode\":\"33069\",\"StartDate\":\"\\/Date(11017920+0000)\\/\",\"State\":\"FL\",\"StateList\":[{\"__type\":\"SelectListItem:#SyMvc\",\"Selected\":false,\"Text\":\"---Please select a State---\",\"Value\":null},{\"__type\":\"SelectListItem:#Syseb.Mvc\",\"Selected\":false,\"Text\":\"Alabama\",\"Value\":\"AL\"},{\"__type\":\"SelectListItem:#Sys.Mvc\",\"Selected\":false,\"Text\":\"Alaska\",\"Value\":\"AK\"}],\"SubCategoryId\":\"124\",\"SubCategoryName\":\"Electronics\",\"Title\":\"Kice stand \",\"UserId\":\"b3bd\",\"ZipCode\":\"45469\"}],\"Status\":\"Success\"}}"
      8. Gson mGson = new Gson()
      9. Container cateResponse = mGson.fromJson(jsonString, Container.class)
      10. System.out.println(cateResponse)
      11. }
      12. }

    11. How to deserialize a JSON file into an ArrayList with nested classes?

      This isn't the thing I was looking for because I don't need to deserialize a json file with a array property inside the class but I need to deserialize a json array of the whole class which contains a nested class. Using gson . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. String json = "[{\"b\" : {\"a\": \"Hello!\"}}, {\"b\" : {\"a\": \"Hi!\"}}, {\"b\" : {\"a\": \"Hello2!\"}}]"
      3. A[] arrA = new A[0]
      4. System.out.println(Arrays.toString(gson.fromJson(json, arrA.getClass())))

    12. Retrofit GSON serialize Date from json string into java.util.date

      So a solution could be to write your custom deserializer. To solve your problem I defined with this deserializer Final step is to create a Gson instance with right adapter My result . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package stackoverflow.questions.q18473011
      2. import com.google.gson.*
      3. import java.lang.reflect.Type
      4. import java.text.*
      5. import java.util.Date
      6. public class FooDeserializer implements JsonDeserializer<Foo> {
      7. public Foo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      8. throws JsonParseException {
      9. String a = json.getAsJsonObject().get("date").getAsString()
      10. String b = json.getAsJsonObject().get("created_at").getAsString()
      11. SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd")
      12. SimpleDateFormat sdfDateWithTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
      13. Date date, created
      14. try {
      15. date = sdfDate.parse(a)
      16. created = sdfDateWithTime.parse(b)
      17. } catch (ParseException e) {
      18. throw new RuntimeException(e)
      19. }
      20. return new Foo(date, created)
      21. }
      22. }

    13. Using GSON to parse a JSON array

      If you change your data to will work fine. Seems to work fine. details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. Wrapper[] arr = gson.fromJson(str, Wrapper[].class)
      3. class Wrapper{ int number
      4. String title
      5. }

    14. How to access nested elements from a JSON using Java (Bing-Search-API)

      it is version 2.2.4.jar. Based on the javadoc of gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html Gson class So you don't need to use the JsonParser directly. details

      Reactions - Positive 6, Negative 3, Others 0

      1. Gson gson = new Gson()
      2. Response response = gson.fromJson(jsonText, Response.class)
      3. Results firstResult = response.getD().getResults().get(0)
      4. System.out.println(firstResult.getMediaUrl())

      Positive Reactions
      1. @LuisLavieri I updated my answer, please note that I had to modify your java classes to get it work, how did you get them?
      2. Thanks buddy.
      3. Thanks, but how can I access MediaUrl?
      4. Thank you, but it's returning null.
      5. Could you take a look to my gist please?
      6. That was perfect.
      Negative Reactions
      1. I'm sorry, I was trying to follow your example.
      2. I tried changing Result.java so it could return a List, and then in my code I tried in a loop thumbnails[i] response.getD().getResults().thumbnail.get(i); , but, it is not working.
      3. Hi, sorry for bothering you again.
      Other Reactions
      1. :(.
      2. I tried that too, but it's throwing a NPE.
      3. But now I was trying to get MediaUrl from Thumbnail.java.
      4. What is happening?
      5. @LuisLavieri continuing the example in the answer: firstResult.getThumbnail().getMediaUrl().
      6. when I try to populate a List from "response.getD().getResults()" it throws me an IllegalException.
      7. @LuisLavieri use the code snippet in my answer for deserialization, that is use Gson class instead of JsonParser.
      8. @LuisLavieri updated my answer, your "root element" is Response, so that's what you have to specify at gson.fromJson(...).
      9. Now it is giving me Type mismatch: cannot convert from Object to BingSearchExample.Results and the option that is giving me is adding a cast to Results which does not work or change result type.
      10. [This is what I tried]( URL_https://gist.github.com/lumalav/6222895 file jsonparser-java).
      11. that one throws me a NPE.
      12. Did you change jsonParser2.java?
      13. I am using this as you mentioned: Gson gson new Gson(); Results res gson.fromJson(jsonText, Results.class); System.out.println( res.getMediaUrl());.

    15. How to convert hash of hashmaps to json in java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Map questionDetails = new HashMap<>()
      2. questionDetails.put("label", descriptionNode.getText())
      3. Map validations = new HashMap<>()
      4. validations.put("compulsary", 1)questionDetails.put("validations", validations)
      5. System.out.println(new Gson().toJson(questionDetails))

    16. parsing json with java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. private static String jsonTxt="{'foo':'bar','coolness':2.0,'altitude':39000,'pilot':{'firstName':'Buzz','lastName':'Aldrin'},'mission':'apollo 11'}"
      2. public static void main(String[] args) throws Exception { Gson gson = new Gson()
      3. MyJson myJson = gson.fromJson(jsonTxt, MyJson.class)
      4. System.out.println(myJson.getFoo())
      5. System.out.println(myJson.getCoolness())
      6. }/** * */package com.test
      7. //JSON representationclass MyJson {public MyJson() {}private String foo
      8. private float coolness
      9. // other attributespublic void setFoo(String foo) { this.foo = foo
      10. }public String getFoo() { return foo
      11. }public void setCoolness(float coolness) { this.coolness = coolness
      12. }public float getCoolness() { return coolness
      13. }}

    17. Mule JSON data to objects

      Have you tried the Google GSon library. There is a sample On the other hand if you want to deserialize the dates that contain arrays you'd better take a look here gson-array-deserialization Gson-Array-deserialization . details

      Reactions - Positive 0, Negative 1, Others 0

      1. Gson gson = new Gson()
      2. Handpoint testing = gson.fromJson(data, Handpoint.class)
      3. System.out.println("Amount: " + testing.getAmount())

      Negative Reactions
      1. @JonB dude, update your question with code, don't put code in comments it is just a mass of crap that is unreadable.
      Other Reactions
      1. My paylaod is taken in herepublic ClientResponse ExtractVariablesFromPayload(@Payload JsonObject jsonObject) {ClientResponse callHandpointRestResponse CallHandpointRest(jsonObject.ccInfo.getCurrency(), jsonObject.ccInfo.getAmount(), jsonObject.ccInfo.getCardNumber(), jsonObject.ccInfo.getExpiryDate()); return callHandpointRestResponse;}This class here I use work with part of the json I wannt@JsonIgnoreProperties({"ad", "dates"})public class JsonObject { @JsonProperty("cc_info") CcInfo ccInfo;}How can I return the rest of payload, when the java class finish execution ?

    18. How to write a basic JSON parsing class

      Uh Well to each his poison I guess. you can create any bean by extending this AbstractMessageObject. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public abstract class AbstractMessageObject { public String toString() { Gson gson = new Gson()
      2. //here mapping Object class name is prefixed to json message so otherwise knows the mapping object return "^" + this.getClass().getName() + "^" + gson.toJson(this)
      3. }

      Other Reactions
      1. OP specified no libraries :-(.

    19. Parsing json object into a string

      For this I used GSON see GSON . There you got the possibility to create a complete JSON-String.Here some example What you need is that you your Class-Attributes-setter and JSON-Attribute names are equivalent. details

      Reactions - Positive 0, Negative 0, Others 0

      1. // Converts a object into a JSON-Stringpublic String convertMyClassObjectToJsonFormat() { MyClass myObject = new MyClass()
      2. Gson gson = new Gson()
      3. return gson.toJson(myObject)
      4. }//Converts a JSON-String into a Java-Class-Objectpublic MyClass convertJsonToMyClassObject( CharBuffer jsonMessage) { Gson gson = new Gson()
      5. return gson.fromJson(jsonMessage.toString(), MyClass.class)
      6. }

    20. Different JSON array response

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. Response response = gson.fromJson(json, Response .class)
      3. List<Gear> gears = response.getGears()

    21. How to convert Java Enum to Json at runtime?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Map tmp = new HashMap<SomeType, String>()
      2. for(SomeType type : SomeType.values()){ tmp.put(type, type.getLabel())
      3. } String desiredJson = new Gson().toJson(tmp)

    22. How is this parseable to Java Objects (JSON)

      Thank you for your help I used Bart Kiers answer now!. You could just parse it into a Map which would print . details

      Reactions - Positive 2, Negative 0, Others 0

      1. String json = "{\n" + " \"1\": {\n" + " \"link\": \"http://www.hfk-bremen.de/t/meisterkurse/n/4-historic-brass-studio\",\n" + " \"title\": \"4. Historic Brass Studio\",\n" + " \"content\": \"Vom 13. bis 16. Mrz 2013 findet das 4. Historic Brass Studio Bremen an der Hochschule fr Knste Bremen statt. Angeboten an den vier Tage authentische historische Spielpraxis fr Trompete, Posaune, Zink und Horn:\",\n" + " \"img\": \"http:\n" + " //www.hfk-bremen.de/sites/default/files/imagecache/event_block_thumb_300w/media/historicbrassstudio_1.jpg\",\n" + " \"type\": \"concerts\"\n" + " },\n" + " \"2\": {\n" + " \"link\": \"http://www.hfk-bremen.de/t/konzerte/n/orgelkonzert-3\",\n" + " \"title\": \"Orgelkonzert\",\n" + " \"content\": \"Studierende der Orgeklassen von KMD Prof. Tilmann Benfer spielen die Choralbearbeitungen von Brahms und Kluge am 14.03.2013 im St. Petri Dom Bremen.\",\n" + " \"img\": \"http://www.hfk-bremen.de/sites/default/files/imagecache/content_start/imagegeneration/Orgelkonzert.png\",\n" + " \"type\": \"concerts\"\n" + " },\n" + " \"3\": {\n" + " \"link\": \"http://www.hfk-bremen.de/t/konzerte/n/musik-im-museum-6\",\n" + " \"title\": \"Musik im Museum\",\n" + " \"content\": \"Konzert mit Clovis Michon (Violoncello) aus der Klasse von Prof. Alexander Baillie am 14.03.2012 um 19.30 Uhr. Auf dem Programm stehen die Solo-Suiten von J.S. Bach No. 1-3, BWV 1007-1009\",\n" + " \"img\": \"http://www.hfk-bremen.de/sites/default/files/imagecache/event_block_thumb_300w/media/musikimmuseum_8.jpg\",\n" + " \"type\": \"concerts\"\n" + " }\n" + "}"
      2. Gson gson = new Gson()
      3. Map map = gson.fromJson(json, Map.class)
      4. System.out.println(((Map)map.get("2")).get("title"))

      Positive Reactions
      1. You're welcome @django.
      2. This works, thank you for helping me learn a bit more about json!.

    23. Sending list in JSON request

      1. 2. details

      Reactions - Positive 4, Negative 0, Others 0

      1. Add gson jar import com.google.gson.Gson
      2. //importGson gson = new Gson()
      3. //create instancegson.toJson(ListData)
      4. //convert it to json

      Positive Reactions
      1. @dfsfsdfsdfsdfsdf Feel free to MArk it is as answer and to click uplink if the answer satisfied you.
      2. Thanks a lot Boss!.
      3. Thanks but we are not using Gson.
      4. Ok thanks so just defining this view in xml file will take care of automatic mapping?
      Other Reactions
      1. Point Number 2 is not related to gson, it is spring.
      2. I update the answer with all changes required.
      3. Or I need to do additional processing in controller?
      4. We are using Jackson.

    24. How return array of items using json object in servlet and how to display using jquery

      Please any one tell me how to do the stuff for this case.........thanks . Convert ArrayList to json using method. details

      Reactions - Positive 0, Negative 1, Others 0

      1. new Gson().toJson(object)

      Negative Reactions
      1. It is not working for me java.lang.reflect.Type listOfTestObject new TypeToken>(){}.getType();String str gson.toJson(commentInfo, listOfTestObject);JsonElement commentObj gson.toJsonTree(str); and myObj.add("commentInfo", commentObj);out.println(myObj.toString()); Is it correct.
      Other Reactions
      1. did you try without toJsonTree means use toJson only?
      2. can you give an example.
      3. I can't understand your answer...
      4. So i can't use toJson directly...
      5. It needs JsonElement.
      6. JsonObject.add() is not allows any string.
      7. Type listOfTestObject new TypeToken>(){}.getType();String s gson.toJson(list, listOfTestObject);ArrayList list2 gson.fromJson(s, listOfTestObject);.
      8. toJson is must need assignment to a string.

    25. GSON mapping null value for POJO properties

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject json = hitRestfulWebService()
      2. Gson gson = new Gson()
      3. // json.toString = "{response":{"job":{ ..."Job job = gson.fromJson(json.toString(), Response.class)

    26. Pass json object to a play-framework action

      You need to bind it manually. In your example the code could be something like Note Gson is provided with play!framework distribution so you are free to use it . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static void putName( String data ) { FullName fname = new Gson().fromJSON(data, FullName.class)
      2. ...}

      Other Reactions
      1. Write you code using gist.github.com, and type the link here to help people understand.
      2. I am not sure what you are talking about.
      3. Does calling a member data pick up the content?

    27. How to serialize and deserialize a JSON object from Google geocode using Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. GoogleGeoCodeResponse result = gson.fromJson(jsonCoord(URLEncoder.encode(address, "UTF-8"))
      3. GoogleGeoCodeResponse.class)
      4. double lat = Double.parseDouble(result.results[0].geometry.location.lat)
      5. double lng = Double.parseDouble(result.results[0].geometry.location.lng)

    28. How to retrieve Date from JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Date date = gson.fromJson(json, Date.class)
      2. //Where gson = new Gson()

    29. Composing a simple JSON response in Java

      Dogbert answer on the link was suitable to your needs imho). using JSON serialization deserialization using google-gson serialization deserialization . details

      Reactions - Positive 3, Negative 0, Others 0

      1. MyObject obj = new MyObject("PEBKAC", false)
      2. new com.google.gson.Gson().toJSON(obj)

      Positive Reactions
      1. Thanks for the code samples.
      2. They highlight some elegant options very well.
      3. I will check out JSONObject as it looks well suited to my scenario.

    30. Composing a simple JSON response in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. MyObject obj = new com.google.gson.Gson().fromJSON(responseAsString, MyObject.class)
      2. obj.getMessage()
      3. obj.getSuccess()

    31. Why does gson not serialize this tutorial code?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class Test { public static void main(String[] args) { BagOfPrimitives obj = new BagOfPrimitives()
      2. System.out.println(obj.value1 + obj.value2 + obj.value3)
      3. Gson gson = new Gson()
      4. System.out.println(gson.toJson(obj))
      5. } static class BagOfPrimitives { private int value1 = 1
      6. private String value2 = "abc"
      7. private transient int value3 = 3
      8. BagOfPrimitives() { // no-args constructor } }}

    32. Mapping between JSON formats in Java

      Like gson. Here is an example that is on their website . details

      Reactions - Positive 0, Negative 0, Others 0

      1. class BagOfPrimitives { private int value1 = 1
      2. private String value2 = "abc"
      3. private transient int value3 = 3
      4. BagOfPrimitives() { // no-args constructor } } //(Serialization) BagOfPrimitives obj = new BagOfPrimitives()
      5. Gson gson = new Gson()
      6. String json = gson.toJson(obj)
      7. ///==> json is {"value1":1,"value2":"abc"} ///Note that you can not serialize objects with circular references since that will result in infinite recursion. //(Deserialization) BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class)
      8. //==> obj2 is just like obj

      Other Reactions
      1. Take a look at the website: URL_https://sites.google.com/site/gson/gson-user - guide.

    33. converting gson to object with java

      And a stub/runner. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. public class Main {
      3. public static void main(String[] args) {
      4. String response =
      5. "{\"json\": {\"errors\": [], \"data\": {\"modhash\": \"dosiom5o6abbbb758729039f04762a05778db4aeeeacd8eb4a\", \"cookie\": \"14756159,2012-08-21T12:05:05,0971bdec35d71af4073cf56ad82fb0ae7c5fe2d1\"}}}"
      6. GSONClass target = new Gson().fromJson(response, GSONClass.class)
      7. System.out.println(target)
      8. }
      9. }

      Positive Reactions
      1. my pleasure!
      2. thanks.
      Other Reactions
      1. the getters and setters are not needed to make this work, so I removed them for clarity and succinctness.
      2. this worked.
      3. :).

    34. JSON to Java Object

      This also did the trick. PhotoDTO Class Definition . details

      Reactions - Positive 1, Negative 0, Others 0

      1. jsonString =[...]
      2. Gson gson = new Gson()
      3. PhotoDTO[] photos = gson.fromJson(jsonString, PhotoDTO[].class)
      4. for(PhotoDTO photo : photos){ System.out.println("photo -> " + photo.getPhoto())
      5. }

      Positive Reactions
      1. Thanks!
      Other Reactions
      1. This worked.The [] in PhotoDTO[] was what I was missing.

    35. Play controller not accepting JSON POST

      Try changing the variable name in your method parameters from json to body. . details

      Reactions - Positive 3, Negative 0, Others 0

      1. public static void index(String body) { Logger.info("content type: %s", request.contentType)
      2. Logger.info("json string: %s", body)
      3. MyObj obj = new Gson().fromJson(body, MyObj.class)
      4. ... ...}

      Positive Reactions
      1. You saved my week.
      2. @Briggs: Thank you man.
      3. Why do they make it like this?
      Other Reactions
      1. They look at your method parameters and try to see if they can bind it to request.params with the same name.
      2. And the post body comes in as request.params.body (and I figured it out the same way you did URL_http://stackoverflow.com/questions/8154980/how-do-i-create-a-custom-binder - for-a-json-body).
      3. This answer needs 100 upvotes.
      4. This worked.
      5. Cannot believe that is the answer, just another reason I don't like Java.

    36. How can I fetch the value from JSON in Java program?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. Map map = gson.fromJson("{\"query\":{\"pages\":{\"3037904\":{\"pageid\":3037904,\"ns\":0,\"title\":\"Kempinski\", \"categories\":[{\"ns\":14,\"title\":\"Category:Companies established in 1897\"},{\"ns\":14,\"title\":\"Category:Hotel chains\"},{\"ns\":14,\"title\":\"Category:Kempinski Hotels\"}]}}}}", HashMap.class)
      3. Map query = (Map) map.get("query")
      4. Map pages = (Map) query.get("pages")
      5. System.out.println(pages.keySet())
      6. Map page = (Map) pages.get("3037904")
      7. System.out.println(page)
      8. System.out.println(page.get("pageid"))

    37. Gson gson = new Gson().toJson(data) - incompatible types

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Employee obj = new Employee()
      2. // Your java object...Gson gson = new Gson()
      3. // convert java object to JSON format,// and returned as JSON formatted stringString json = gson.toJson(obj)
      4. response.getWriter().write(json)

    38. Gson gson = new Gson().toJson(data) - incompatible types

      CODE Line 60 64 ERRORS Line 60 Line 64 Does anyone know how to properly do what I'm trying. It certainly looks from your error messages that it should be which seems to address both of those errors. details

      Reactions - Positive 0, Negative 0, Others 0

      1. String gson = new Gson().toJson(data)

    39. How to deserialize a keyless array with GSON?

      This would automatically map the values to the right property. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. import java.util.List
      3. public class GSonTest {
      4. public static void main(final String[] args) {
      5. Gson gson = new Gson()
      6. System.out.println(
      7. gson.fromJson(
      8. "{ \"type\": \"Point\", \"coordinates\": [ 16.7594706041998, 43.148716514354945 ] }",
      9. Geometry.class))
      10. }
      11. public static class Geometry {
      12. List<Float> coordinates
      13. public List<Float> getCoordinates() {
      14. return coordinates
      15. }
      16. public void setCoordinates(final List<Float> coordinates) {
      17. this.coordinates = coordinates
      18. }
      19. @Override
      20. public String toString() {
      21. return "Geometry [coordinates=" + coordinates + "]"
      22. }
      23. }
      24. }

      Positive Reactions
      1. Could you please add the relevant Java code?
      2. I would go for Double since Float shortens the values.
      Other Reactions
      1. Also, as far as I understood I do not need to add getters and setters if my member is public (I use it in an Android enviroment).
      2. this is right :).

    40. Read an array of JSON in JAVA

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.test
      2. import com.google.gson.Gson
      3. public class GSonExample {
      4. public static void main(String[] args) {
      5. String json =
      6. "{\"name\":\"Duke\",\"address\":\"Menlo Park\",\"dateOfBirth\":\"Feb 1, 2000 12:00:00 AM\"}"
      7. Gson gson = new Gson()
      8. User student = gson.fromJson(json, User.class)
      9. System.out.println("student.getName() = " + student.getName())
      10. System.out.println("student.getAddress() = " + student.getAddress())
      11. System.out.println("student.getDateOfBirth() = " + student.getDateOfBirth())
      12. }
      13. }
      14. public class User {
      15. private String name
      16. private String address
      17. private String dateOfBirth
      18. public String getName() {
      19. return name
      20. }
      21. public void setName(String name) {
      22. this.name = name
      23. }
      24. public String getAddress() {
      25. return address
      26. }
      27. public void setAddress(String address) {
      28. this.address = address
      29. }
      30. public String getDateOfBirth() {
      31. return dateOfBirth
      32. }
      33. public void setDateOfBirth(String dateOfBirth) {
      34. this.dateOfBirth = dateOfBirth
      35. }
      36. }

    41. Parse Json to Java

      It works thank u. You could have just written This should do all the work of your two complex methods parseGson_Ressources and parseGson_Ressources. details

      Reactions - Positive 0, Negative 2, Others 0

      1. public Ressources[] parseGson_Ressources(String jsonToParse) { Gson gson = new Gson()
      2. Ressources[] resources = gson.fromJson(jsonToParse, Ressources[].class)
      3. }

      Negative Reactions
      1. Correct me if I am wrong, but List.class is actually not valid in Java.
      2. Damn, you guys are fast!
      Other Reactions
      1. But he can use this alternative with GSon: Type collectionType new TypeToken>(){}.getType(); and pass collectionType instead of the class.
      2. @GuillaumePolet - 10x for the comment you are right.
      3. Did you really read all this bunch of code?
      4. :).

    42. Read/Parse JSON with Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonContainer data = new Gson().fromJson(content, JsonContainer.class)

    43. How to parse nested JSON with GSON

      I'd create another Bean for Activities since it is a JSON object in itself. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. class Assignment { private String id
      2. private List<Activity> activities
      3. //getters and setters for this. public String getId() { return id
      4. }}class Activity { private String activity
      5. //Getters and setters}Gson mGson= new Gson()
      6. assignmentList=mGson.fromJson(json, AssignmentList.class)
      7. assignmentList.getAssignments().get(0).getActivities.get(1)

      Positive Reactions
      1. Great!
      2. Thank you!
      Other Reactions
      1. System.out.println("Activity: " + assignmentList.getAssignments().get(0).getActivities().get(1).getActivity());.

    44. parsing Json with gson nested

      Easily extendisible to add differernt objects. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. /*Here we do the following steps* 1. create the data* 2. convert data to Json String using GSON* 3. JSon String is used to populate the data bean using GSON.** Integers will be used as the key.*/ public class CreateAccessGSON(){ public static void main(String[] args) { Gson gson = new Gson()
      2. //instantiate gson here. //Creating the Data Object. HashMap<Integer,AdminBean> tmpAdminMap = new HashMap<Integer,AdminBean>()
      3. AdminBean adminOne1 = new AdminBean()
      4. adminOne1.setName("Joe")
      5. tmpAdminMap.put(1,adminOne1)
      6. // key is an Integer 1 AdminBean adminOne2 = new AdminBean()
      7. adminOne2.setName("Blow")
      8. tmpAdminMap.put(2,adminOne2)
      9. // key is an Integer 2 //Set the value of the Map. DataObjectBean dataObjectBean = new DataObjectBean()
      10. dataObjectBean.setAdminMap(tmpAdminMap)
      11. String jsonString = gson.toJson(dataObjectBean)
      12. System.out.println(jsonString )
      13. // print the Json String. //Output will be as follows /* { "adminMap" : { "1" : {"name":"Joe"} , "2" : {"name":"Blow"} } } */ // Code to Convert Json String to the Associated object. DataObjectBean accessDataObjectBean = gson.fromJson(jsonString ,DataObjectBean)
      14. HashMap<Integer,AdminBean> retrieveAdminMap = accessDataObjectBean.getAdminMap()
      15. System.out.println(retrieveAdminMap.get(1).getName())
      16. // Joe System.out.println(retrieveAdminMap.get(2).getName())
      17. // Blow //get number of keys, we use the hashmap size. System.out.println("Num of keys : " + retrieveAdminMap.size())
      18. // Num of keys : 2 // You can use the Java Iterator to access each key and their values Set<Integer> setKey = retrieveAdminMap.keySet()
      19. for( Integer keys : setKey ) { AdminBean eachAdmin = retrieveAdminMap.get(keys)
      20. System.out.println(eachAdmin.getName())
      21. } }} //This class will store the Admin data. You can have more nested classes here.// This class can further have more maps.public class AdminBean{ private String name = ""
      22. public String getName() { return name
      23. } public String setName(String name) { this.name = name
      24. }}// This main Java Bean which will be used to generate the JSON.// Since we need as Integer as key, we use the HashMap to store it.// HashMaps will allow storing unlimited Integers.public class DataObjectBean{ private HashMap<Integer,AdminBean> adminMap = new HashMap<Integer,AdminBean>()
      25. public String getAdminMap () { return adminMap
      26. } public String setAdminMap (String adminMap ) { this.name = adminMap
      27. }}

      Positive Reactions
      1. thanks a lot man!
      2. it was very useful!.

    45. Gson deserialization: set final field

      For example On the other hand for instance creation during deserialization since Gson uses sun.misc.Unsafe and not a user-defined constructor assignments of final fields explicitly defined in any constructor are not respected. For example In summary during vanilla deserialization it's not possible to reassign a final field assignment with any data from the incoming JSON though it may appear to be possible if the final field assignment is occurring in a user defined constructor. details

      Reactions - Positive 1, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. public class GsonFoo{ public static void main(String[] args) { // {"name":"Fred","id":42} String json1 = "{\"name\":\"Fred\",\"id\":42}"
      3. System.out.println(new Gson().fromJson(json1, Bar1.class))
      4. // output: // Bar1: name=Fred, id=42 }}class Bar1{ String name = "BLANK"
      5. final int id
      6. Bar1() { id = -1
      7. } @Override public String toString() { return String.format("Bar1: name=%s, id=%d", name, id)
      8. }}

      Positive Reactions
      1. If it's a primitive type or assigned to something else, like a string, gson won't touch it.
      Negative Reactions
      1. Then Gson is even more inconsistent than I guessed it was.
      Other Reactions
      1. If i have a field that is final and assigned to null (no constructor), gson will fill that field.
      2. Ack.
      3. I found out more behaviour.

    46. Gson deserialization: set final field

      Gson 1.7.1 and 2.0 both respect final field assignments during vanilla deserialization operations and the initial final field assignments are not altered. For example On the other hand for instance creation during deserialization since Gson uses sun.misc.Unsafe and not a user-defined constructor assignments of final fields explicitly defined in any constructor are not respected. details

      Reactions - Positive 1, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. public class GsonFoo{ public static void main(String[] args) { // {"name":"Fred","id":42} String json1 = "{\"name\":\"Fred\",\"id\":42}"
      3. System.out.println(new Gson().fromJson(json1, Bar1.class))
      4. // output: // Bar1: name=Fred, id=-1 }}class Bar1{ String name = "BLANK"
      5. final int id = -1
      6. @Override public String toString() { return String.format("Bar1: name=%s, id=%d", name, id)
      7. }}

      Positive Reactions
      1. If it's a primitive type or assigned to something else, like a string, gson won't touch it.
      Negative Reactions
      1. Then Gson is even more inconsistent than I guessed it was.
      Other Reactions
      1. If i have a field that is final and assigned to null (no constructor), gson will fill that field.
      2. Ack.
      3. I found out more behaviour.

    47. Parsing JSon Data using java (google-gson)

      Your data structures should reflect the data you are trying to de-serialize. For example you could use something of this form The guid property of the JSON is mapped to the guid property of the Data type. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class Data {
      2. private Map<String, String> guid
      3. public Map<String, String> getGuid() {
      4. return guid
      5. }
      6. public void setGuid(Map<String, String> guid) {
      7. this.guid = guid
      8. }
      9. public static void main(String[] args) {
      10. String json =
      11. "{\"guid\":{"
      12. + "\"uri\":\"http://social.yahooapis.com/v1/me/guid\","
      13. + "\"value\":\"123456789\"}}"
      14. Data data = new Gson().fromJson(json, Data.class)
      15. System.out.println(data.getGuid().get("uri"))
      16. }
      17. }

    48. JSON-encode an array of objects and arrays in Java for PHP

      Personally I'd suggest you skip the clever object binding stuff and look at the //google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html JSONWriter class instead. This is a lot quicker than the method it doesn't do refection magic behind the scenes) uses less memory and scales better. details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson.toJson()

    49. JSON-encode an array of objects and arrays in Java for PHP

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. String jsonString = gson.toJson(daticompleti)

    50. Dealing with randomly generated and inconsistent JSON field/key names using GSON

      I'm pleased to report that with GSON 2.0 supports default maps and lists without effort. Deserialize like this The result will be a Map with String keys and either String or Map values. details

      Reactions - Positive 2, Negative 2, Others 0

      1. Object o = new Gson().fromJson(json, Object.class)

      Positive Reactions
      1. Thanks!.
      2. With latest Gson (2.2.4) it works fine.
      Negative Reactions
      1. I'll be damned.
      2. Hmm, are you sure Gson works this way for arbitrary JSON field names?
      Other Reactions
      1. No wait, my SO test project was using Gson 1.4.
      2. How to do it for the JSON format at URL_http://stackoverflow.com/a/20442943/56285 ?
      3. I gave it a try, but it just throws com.google.gson.JsonParseException: Type information is unavailable, and the target object is not a primitive.

    51. Dealing with randomly generated and inconsistent JSON field/key names using GSON

      Deserialize like this The result will be a Map with String keys and either String or Map values. Serialize that map back to JSON like this We hope to release GSON 2.0 in October 2012. details

      Reactions - Positive 2, Negative 2, Others 0

      1. String json = new Gson().toJson(o)

      Positive Reactions
      1. Thanks!.
      2. With latest Gson (2.2.4) it works fine.
      Negative Reactions
      1. I'll be damned.
      2. Hmm, are you sure Gson works this way for arbitrary JSON field names?
      Other Reactions
      1. No wait, my SO test project was using Gson 1.4.
      2. How to do it for the JSON format at URL_http://stackoverflow.com/a/20442943/56285 ?
      3. I gave it a try, but it just throws com.google.gson.JsonParseException: Type information is unavailable, and the target object is not a primitive.

    52. Gson de-serialize to Map generic type

      1 Make the Map of type String String though you lose the types you can still get the values back properly 2 Put the values into a bean class first and then Serialize that. Both defeat the purpose of what you are trying to do but it is in googles court to fix this bug I believe. details

      Reactions - Positive 0, Negative 2, Others 0

      1. public class myObj{ String myStr
      2. int myInt
      3. boolean myBool
      4. //get and set methods}public static void main(String args[]){ MyObj o = new MyObj()
      5. o.setMyStr("str-value")
      6. Gson gson = new Gson()
      7. String json = gson.toJson(o)
      8. o = gson.fromJson(json, MyObj.class)
      9. }

      Negative Reactions
      1. Its a blocking issue anyway.
      2. So far it seems Gson expects a static type to be supplied rather than type Object.
      Other Reactions
      1. See the problem, thanks for clarifying.

    53. Parsing JSON from URL

      Then you need to parse it and here you have some options). GSON full example) Outputs Try the java API from json.org . details

      Reactions - Positive 1, Negative 0, Others 0

      1. static class Item { String title
      2. String link
      3. String description
      4. }static class Page { String title
      5. String link
      6. String description
      7. String language
      8. List<Item> items
      9. }public static void main(String[] args) throws Exception { String json = readUrl("http://www.javascriptkit.com/" + "dhtmltutors/javascriptkit.json")
      10. Gson gson = new Gson()
      11. Page page = gson.fromJson(json, Page.class)
      12. System.out.println(page.title)
      13. for (Item item : page.items) System.out.println(" " + item.title)
      14. }

      Positive Reactions
      1. Ah, good point updated.
      Other Reactions
      1. this will parse a url ?
      2. URL_http://json.org/java .
      3. @Salah Yahya: Added GSON example + how to download an url.
      4. 'java' tag indicates that he doesn't want to use javascript.

    54. gson and json deserializing

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Details details = new Gson().fromJson(result, Details.class)

    55. Gson - Automatic quote (") escaping?

      Maybe I'm not understanding your question but I was able to get GSON to handle Strings with quotes without any settings or changes. Output Maybe I don't understand what you're asking. details

      Reactions - Positive 1, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. public class GSONTest {
      3. public String value
      4. public static void main(String[] args) {
      5. Gson g = new Gson()
      6. GSONTest gt = new GSONTest()
      7. gt.value = "This is a \"test\" of quoted strings"
      8. System.out.println("String: " + gt.value)
      9. System.out.println("JSON: " + g.toJson(gt))
      10. }
      11. }

      Positive Reactions
      1. IMHO the very fact that you were able to get the object in Javascript means it was correctly formed JSON.
      Negative Reactions
      1. Yeah sorry you are right !With a request from my browser (typing url) I get the valid JSON.But when I get the JSON with Javascript, with jQuery jsonP, escape symbols are removed ...
      Other Reactions
      1. This is really strange.
      2. @Stphane Piette: Aren't you viewing the string as read in by Javascript, i.e., after unescaping?
      3. +1 for providing an almost identical answer to mine a minute earlier :-).

    56. How to convert HTTP Request Body into JSON Object in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Object o = new Gson().fromJson(Content, RetrieveData.class)
      2. data = (RetrieveData)o
      3. // Get Meta data.getName()
      4. // Example data.getFirstName()
      5. // Example2 // Get Data data.get(0).getTitle()
      6. // position 0 : ecaetra data.get(0).getDescription()
      7. // position 0 : qwerty

    57. How to Return Different Objects via Asynctask in Android

      Then a switch sends the actual json string to the appropriate method that can manipulate the response as necessary. Simplified pseudocode I think this is more less what Pompe de velo was saying however I am just making my a_parameter_match based on the status code rather than something within the json. details

      Reactions - Positive 0, Negative 0, Others 0

      1. private void getGameData(){ new MyAsyncTask(this, MyAsyncTask.OBJ_GAME_DATA).execute()
      2. }static class MyAsyncTask extends AsyncTask<String, Integer, String> { private int outputObjectType
      3. protected static final int OBJ_GAME_DATA = 0
      4. protected static final int OBJ_OTHER_DATA = 1
      5. protected static final int OBJ_DIFFERENT_DATA = 2
      6. protected static final int OBJ_SERVER_ERROR = 3
      7. MyAsyncTask(MyActivity activity, int expectedObject){ outputObjectType = expectedObject
      8. } doInBackground(){ if(httpStatusCode >= 400){ outputObjectType = MyAsyncTask.OBJ_SERVER_ERROR
      9. } return jsonStringFromServer
      10. } onPostExecute(String json){ switch(outputObjectType){ case MyAsyncTask.OBJ_SERVER_ERROR: serverError(json)
      11. break
      12. case MyAsyncTask.OBJ_GAME_DATA: processGameData(json)
      13. break
      14. // .... } }}private void serverError(String json){ ServerError se = new Gson().fromJson(json, ServerError.class)
      15. Log.d(TAG, se.getErrorMessage())
      16. }private void processGameData(String json){ GameData gd = new Gson().fromJson(json, GameData.class)
      17. // .......}

    58. Getting data from JSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package sg.java.play_sof_json_6596072
      2. import com.google.gson.Gson
      3. public class App {
      4. public static void main(String[] args) {
      5. Gson gson = new Gson()
      6. String jsonString =
      7. "{\"DebugLogId\":\"1750550\",\"RequestId\":\"17505503\",\"Result\":{\"Code\":\"\",\"DebugLogId\":\"1750550\",\"Message\":\"\"},\"Suggestions\":[{\"Ranking\":\"1\",\"Score\":\"60\",\"Title\":\"This is a test message 1\"},{\"Ranking\":\"2\",\"Score\":\"60\",\"Title\":\"This is a test message 2\"}]}"
      8. Debug obj = (Debug) gson.fromJson(jsonString, Debug.class)
      9. System.out.println(obj.getSuggestionList().get(1).getTitle())
      10. }
      11. }

    59. Can't Convert string to JsonArray

      with the keyword import" as shown below. . details

      Reactions - Positive 1, Negative 1, Others 0

      1. import com.google.gson.*

      Positive Reactions
      1. You mean getting the first element ([\"110917 \", 3.0099999999999998, -0.72999999999999998, 2.8500000000000001, 2.96, 685.0, 38603.0]) of JsonArray "trade"?
      Negative Reactions
      1. Here typo mistaken for import in the question .actually added in source..thanks.
      Other Reactions
      1. Is it Possible to split the JsonArray?
      2. Try using "trade.get(0)".

    60. How to find specified name and its value in JSON-string from Java?

      Specific to the question asked here's a working solution. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. public class Foo {
      3. static String jsonInput =
      4. "{"
      5. + "\"name\":\"John\","
      6. + "\"age\":\"20\","
      7. + "\"address\":\"some address\","
      8. + "\"someobject\":"
      9. + "{"
      10. + "\"field\":\"value\""
      11. + "}"
      12. + "}"
      13. String age
      14. public static void main(String[] args) throws Exception {
      15. Gson gson = new Gson()
      16. Foo thing = gson.fromJson(jsonInput, Foo.class)
      17. if (thing.age != null) {
      18. System.out.println("age is " + thing.age)
      19. } else {
      20. System.out.println("age element not present or value is null")
      21. }
      22. }
      23. }

    61. Using GSON to parse array with multiple types

      Applied to the example in the original question above if it's acceptable to treat all of the values as Strings then deserialization becomes simple. Unfortunately with Gson I've not been able to figure out a simple deserialization approach that would allow for better binding to more specific and mixed types in an array since Java doesn't provide a syntax for defining a mixed type array. details

      Reactions - Positive 0, Negative 0, Others 0

      1. // output:// hello 1 2 // world 3 2 public class Foo{ static String jsonInput = "[" + "[\"hello\",1,[2]]," + "[\"world\",3,[2]]" + "]"
      2. public static void main(String[] args) { Gson gson = new Gson()
      3. String[][] data = gson.fromJson(jsonInput, String[][].class)
      4. for (String[] data2 : data) { for (String data3 : data2) { System.out.print(data3)
      5. System.out.print(" ")
      6. } System.out.println()
      7. } }}

    62. Converting json string to java object?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. class DataWrapper {
      2. public Data data
      3. public static DataWrapper fromJson(String s) {
      4. return new Gson().fromJson(s, DataWrapper.class)
      5. }
      6. public String toString() {
      7. return new Gson().toJson(this)
      8. }
      9. }
      10. class Data {
      11. public List<Translation> translations
      12. }
      13. class Translation {
      14. public String translatedText
      15. }

    63. Using Gson to unserialize an array of objects

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String str = "{\"status\": \"OK\","+ "\"usage\": \"By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html\","+ "\"url\": \"http://www.theage.com.au/world/aussie-trying-to-make-a-difference-gunned-down-20110510-1egnv.html\","+ "\"language\": \"english\","+ "\"keywords\": ["+ "{"+ "\"text\": \"Mr McNichols\","+ "\"relevance\": \"0.99441\""+ "},"+ "{"+ "\"text\": \"Ms Benton\","+ "\"relevance\": \"0.392337\""+ "},"+ "{"+ "\"text\": \"Detroit\","+ "\"relevance\": \"0.363931\""+ "},"+ "{"+ "\"text\": \"Crocodile Hunter\","+ "\"relevance\": \"0.350197\""+ "}"+ "]"+ "}"
      2. Gson gson = new Gson()
      3. MyJSON mj = gson.fromJson(str, MyJSON.class)
      4. System.out.println(mj.language)
      5. for(Keyword k: mj.keywords) System.out.println(k.text+":"+k.relevance)

    64. How to convert String to JSONObject in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. class Phone { public String phonetype
      2. public String cat
      3. }...String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}"
      4. Gson gson = new Gson()
      5. Phone fooFromJson = gson.fromJson(jsonString, Phone.class)
      6. ...

    65. How to convert String to JSONObject in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. BagOfPrimitives obj = new BagOfPrimitives()
      2. Gson gson = new Gson()
      3. String json = gson.toJson(obj)
      4. ==> json is {"value1":1,"value2":"abc"}

    66. Creating GSON Object

      Figured it out how to do it correctly using Java Objects. Implementation of Creator java class. details

      Reactions - Positive 0, Negative 0, Others 0

      1. Creator creator = new Creator("John")
      2. new Gson().toJson(creator)

    67. Java - Gson parsing nested within nested

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. ResponseData responseData = new Gson().fromJson(json, ResponseData.class)

    68. How to sort JSON object in java?

      Use-GSON-to-parse-it-to-collection-of-objects Example If you want to create JSON from Object. . details

      Reactions - Positive 5, Negative 1, Others 0

      1. Person p = new Person()
      2. p.setName("Jigar")
      3. p.setAge(22)
      4. String jsonStr = new com.google.gson.Gson().toJson(obj)

      Positive Reactions
      1. Thanks, But I get this object at dynamically(when i called web service) Is it possibile to convert json object to string using tostring() method or any onther method require please help me.
      2. please explain clearly.
      3. Thank you, My last Question is for example object1 is my jsonobject can i convert this json object directly to string type means String jsonstr= object1; but you have taken a class which have the data belongs to json object In my project i am getting this data dynamically means data may change day by day.it is not possible to write this type of class every time.
      4. @venkatesh if you are asking to create JSON from Object than its very well possible using new com.google.gson.Gson().toJson(obj);.
      5. Thanks, JSONObject obj= /** json object data / then String str obj.toString(); is it correct ?
      Negative Reactions
      1. sorry for my english.
      Other Reactions
      1. @venkatesh see updated answer.

    69. How to sort JSON object in java?

      Parse these JSON to COllection of Objects and use comparator to sort it using your preferred field. Use-GSON-to-parse-it-to-collection-of-objects Example If you want to create JSON from Object. details

      Reactions - Positive 5, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. class Person { private int age
      3. private String name
      4. }String json = "{'age':22,'name':'Jigar'}"
      5. Gson gson = new Gson()
      6. TestJsonFromObject obj = gson.fromJson(json, Person.class)

      Positive Reactions
      1. Thanks, But I get this object at dynamically(when i called web service) Is it possibile to convert json object to string using tostring() method or any onther method require please help me.
      2. please explain clearly.
      3. Thank you, My last Question is for example object1 is my jsonobject can i convert this json object directly to string type means String jsonstr= object1; but you have taken a class which have the data belongs to json object In my project i am getting this data dynamically means data may change day by day.it is not possible to write this type of class every time.
      4. @venkatesh if you are asking to create JSON from Object than its very well possible using new com.google.gson.Gson().toJson(obj);.
      5. Thanks, JSONObject obj= /** json object data / then String str obj.toString(); is it correct ?
      Negative Reactions
      1. sorry for my english.
      Other Reactions
      1. @venkatesh see updated answer.

    70. JSON Serialize / Deserialize generic type with google-gson

      Btw I prefer google-gson . In Java you must pass actual type-erased class not just type parameter so data binders know what type to use so something like but this is usually just needed for deserialization when serializing you have an instance with a class which libraries can use. details

      Reactions - Positive 2, Negative 1, Others 0

      1. public static T LoadFromJSONString<T>(string strRequest, Class<T> type){ Gson gson = new Gson()
      2. return gson.fromJson(strRequest, type)
      3. }

      Positive Reactions
      1. Interfaces typically require type parameter so that explicit passing of classes (Response.class is of type Class) is compatible with type parameter; but it is more of a nice to have feature.So you must pass the Class to bind to; type parameter T is not enough for Java to figure out actual real type.
      2. But the thing is that, when I use Class.forName(), the return type must be Object instead of Response, which I have to state clearly like this: Response rp (Response) LoadFromJSONString(resString, Class.forName("com.example.Response")).
      Negative Reactions
      1. Since Class.forName() returns a Class, you do need to do some casting; but while ugly, this does not prevent it from working.
      Other Reactions
      1. You can use Class.forName("com.example.Response") to find it.
      2. Yes, I've already tried.
      3. Hmm, but suppose I only have class info as string, for example String clazz "com.example.Response", so how can I use this code?

    71. JSON Serialize / Deserialize generic type with google-gson

      If you're not keen on making instances of the Gson object everytime you can of course keep that one static at least since it doesn't need any type parameters when created. This should work . details

      Reactions - Positive 0, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. public class GenericClass {
      3. private static Gson gson = new Gson()
      4. public static <T> T loadFromJSONString(String strRequest) {
      5. return (T) gson.fromJson(strRequest, T.class)
      6. }
      7. public static <T> String dumpToJSONString(T rq) {
      8. return gson.toJson(rq)
      9. }
      10. }

      Negative Reactions
      1. This line causes problems:return (T) gson.fromJson(strRequest, T.class);.
      Other Reactions
      1. same as my answer, T.class doesn't work.
      2. Hmm, wait.
      3. That won't work.

    72. How do I provide the following json output using java

      Gson considers both of these as very important design goals. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. class Person { private int age = 10
      3. private String name = "jigar"
      4. }Person obj = new Person()
      5. Gson gson = new Gson()
      6. String json = gson.toJson(obj)

    73. Convert JSON to HashMap using Gson in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Data data = new Gson().fromJson(json, Data.class)

    74. Converting JSON to Java

      You have a JSON object with several properties of which the groups property represents an array of nested objects of the very same type. This can be parsed with Gson the following way Fairly simple isn't it. details

      Reactions - Positive 6, Negative 3, Others 0

      1. package com.stackoverflow.q1688099
      2. import java.util.List
      3. public class Test {
      4. public static void main(String... args) throws Exception {
      5. String json =
      6. "{"
      7. + "'title': 'Computing and Information systems',"
      8. + "'id' : 1,"
      9. + "'children' : 'true',"
      10. + "'groups' : [{"
      11. + "'title' : 'Level one CIS',"
      12. + "'id' : 2,"
      13. + "'children' : 'true',"
      14. + "'groups' : [{"
      15. + "'title' : 'Intro To Computing and Internet',"
      16. + "'id' : 3,"
      17. + "'children': 'false',"
      18. + "'groups':[]"
      19. + "}]"
      20. + "}]"
      21. + "}"
      22. // Now do the magic. Data data = new Gson().fromJson(json, Data.class)
      23. // Show it. System.out.println(data)
      24. }
      25. }
      26. class Data {
      27. private String title
      28. private Long id
      29. private Boolean children
      30. private List<Data> groups
      31. public String getTitle() {
      32. return title
      33. }
      34. public Long getId() {
      35. return id
      36. }
      37. public Boolean getChildren() {
      38. return children
      39. }
      40. public List<Data> getGroups() {
      41. return groups
      42. }
      43. public void setTitle(String title) {
      44. this.title = title
      45. }
      46. public void setId(Long id) {
      47. this.id = id
      48. }
      49. public void setChildren(Boolean children) {
      50. this.children = children
      51. }
      52. public void setGroups(List<Data> groups) {
      53. this.groups = groups
      54. }
      55. public String toString() {
      56. return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups)
      57. }
      58. }

      Positive Reactions
      1. I just commented on reference to expected good performance.Feature-set wise Jackson handles all the same nesting, layering, generics, so that's not where speed difference comes from.Having getters and setters does not impact performance in any measurable way (for packages I am aware of), so definitely can have them there.
      2. Thanks BalusC, I used Gson and the concept is quite simple to grasp.
      3. Maybe in a later version of the app it will be removed for a faster solution.
      4. Wrt speed, if it's fast enough, it's fast enough.
      5. For some reason it made me chuckle.
      6. It is fast enough, sure if you see what it all can do with javabeans, nested javabeans and generics.
      Negative Reactions
      1. While GSON has reasonable feature set, I thought performance was sort of weak spot (as per [ URL_http://www.cowtowncoder.com/blog/archives/2009/09/entry_326.html])As to example: I thought GSON did not really need setters, and was based on fields.
      2. @BalusC : Actually I need to convert mysql data to json (xml) and vice-versa.
      3. It is not the fastest possible solution but it is simple enough to program to justify the lack of performance for the user until now.
      Other Reactions
      1. ?
      2. The javabean getters/setters have other purposes in other layers and does not slowdown so I would just keep them there.
      3. +1 for the "package com.stackoverflow.q1688099;".
      4. Have you actually measured it?
      5. Any link?
      6. I use it in an android app.
      7. @Fahim: scroll down in the code example.
      8. Performant?
      9. So code could be simplified slightly.
      10. Do I need to create any class?
      11. what is Data here?

    75. Converting JSON to Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson#fromJson()

  5. json array in hashmap using google gson

    Your JSON is an array of objects not anything resembling a HashMap. If you mean you're trying to convert that to a List of HashMaps then that's what you need to do Edit to add from comments below If you would like to deserialize to an array of Country POJOs which is really the better approach) it's as simple as That said it's really better to use a Collection . .. details

    1. Type listType = new TypeToken<List<Country>>(){}.getType()
    2. List<Country> countryList = gson.fromJson(myJsonString, listType)

    Positive Reactions
    1. Well, since your JSON isn't a hashmap, and your data isn't anything that you could "just put in a hashmap" ... your question makes absolutely no sense then.
    Other Reactions
    1. when i try to get it in a country class array all field are null Type listType new TypeToken() {}.getType(); country[] carray=gson.fromJson(sb.toString(), listType).
    2. not a list of hashmap in a single hashmap.
    3. No i just need to put all data in to hashmap.

    • See Also (13)
    1. Java - Multiple GSON?

      i.e. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. Type collectionType = new TypeToken<Map<String, Data>>(){}.getType()
      3. Map<String, Data> datas = gson.fromJson(json, collectionType)
      4. Data data1 = datas.get("data1")

      Other Reactions
      1. I edit my question.
      2. You wouldn't need to create 100 classes you would just have 100 instances of class Data.

    2. Java List of custom objects inside response object not populated with GSON unmarshaller

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Type fooType = new TypeToken<Foo<Bar>>() {}.getType()
      2. gson.toJson(foo, fooType)
      3. gson.fromJson(json, fooType)

    3. How to convert complex Java object into JSON

      Can u plz see it. Add TypeToken Use Token if you want to serialize/de the Collection Fixed Output . details

      Reactions - Positive 2, Negative 0, Others 0

      1. Type type = new TypeToken<ListRow<JsonTest>>() {}.getType()
      2. System.out.println(gson.toJson(dataList, type))

      Positive Reactions
      1. Don't forget to accept the answer, is a another good way to say "thank you" :).
      2. thanks a lot Maxim.
      Other Reactions
      1. I got the solution.

    4. why the TypeToken construction in Gson is so weird?

      Thanks bro. means you are creating an anonymous-inner-class that extends TypeToken<Collection<Integer. details

      Reactions - Positive 0, Negative 0, Others 0

      1. new TypeToken<Collection<Integer>>(){}

    5. Parsing JSON to POJO using GSON

      List must be in '. EDIT try this for converting to list Follow-this-link . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Type collectionType = new TypeToken<Collection<Integer>>(){}.getType()
      2. Collection<Integer> ints2 = gson.fromJson(json, collectionType)

    6. How return array of items using json object in servlet and how to display using jquery

      Now you will get a jsonarray of jsonobjects then you can pass it like json to server and vice versa. Array list is a collection so follow this Examples gson-user-guide for displaying json using jquery follow this link. details

      Reactions - Positive 0, Negative 1, Others 0

      1. Type collectionType = new TypeToken<Collection<Integer>>(){}.getType()
      2. Collection<Integer> ints2 = gson.fromJson(json, collectionType)

      Negative Reactions
      1. It is not working for me java.lang.reflect.Type listOfTestObject new TypeToken>(){}.getType();String str gson.toJson(commentInfo, listOfTestObject);JsonElement commentObj gson.toJsonTree(str); and myObj.add("commentInfo", commentObj);out.println(myObj.toString()); Is it correct.
      Other Reactions
      1. did you try without toJsonTree means use toJson only?
      2. can you give an example.
      3. I can't understand your answer...
      4. So i can't use toJson directly...
      5. It needs JsonElement.
      6. JsonObject.add() is not allows any string.
      7. Type listOfTestObject new TypeToken>(){}.getType();String s gson.toJson(list, listOfTestObject);ArrayList list2 gson.fromJson(s, listOfTestObject);.
      8. toJson is must need assignment to a string.

    7. gson: parametrized fromJson depending on the Type

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. PostMessage m = getMessage(request.getReader(), new TypeToken<PostMessage>() {})

    8. Self circular reference in Gson

      Maybe you could try this you will get a good result. The magic occurs here The entire code is JSON file is . details

      Reactions - Positive 1, Negative 1, Others 0

      1. new TypeToken<Collection<Category>>() {}.getType()

      Positive Reactions
      1. Thanks.
      Negative Reactions
      1. The TypeToken thing worked just fine, although I had to adapt your answer a little bit to my case since ArrayOfCategory and Category was just one example but I had to consider a more general case.
      Other Reactions
      1. Cheers.
      2. If you're curious I updated my question.

    9. GSON-JSON Deserialize Object in Class

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Type type = new TypeToken<ProtoQuery<ProtoAuth>>() {}.getType()
      2. ProtoQuery<ProtoAuth> deserializedOBJ = gson.fromJson(json, type)

    10. How do I populate List<Object> from JSON response

      Use Gson it will be as simple as Gson is a powerfull open source library that allows an easy mapping from POJOs to Json and the other way around. Use this Code hope this will help you. details

      Reactions - Positive 0, Negative 0, Others 0

      1. Type collectionType = new TypeToken<List<Your_Object>>() { }.getType()
      2. List<Your_Object> your_Object = gson.fromJson(jsonString, collectionType)

    11. Trouble with Gson serializing an ArrayList of POJO's

      Particularly when deserializing JSON it needs that information to be able to determine what type of object it should deserialize each array element to. This is documented in the guide#TOC-Collections-Examples Gson-user-guide . details

      Reactions - Positive 7, Negative 5, Others 0

      1. Type listOfTestObject = new TypeToken<List<TestObject>>(){}.getType()
      2. String s = gson.toJson(list, listOfTestObject)
      3. List<TestObject> list2 = gson.fromJson(s, listOfTestObject)

      Positive Reactions
      1. You just cleared it up for me.
      2. Hope you don't mind.
      3. Thanks for the tip.
      4. How does the use of Type apply in that case to deserialize using something like MyCustomClass obj gson.fromJson(json, MyCustomClass.class).
      5. Thank you very much.
      6. I may likely have another question regarding serialization of a Queue soon!
      7. Does the same hold true for nested HashMap?
      Negative Reactions
      1. I have never used Type's before, and was confused at its use.
      2. If so, there's no problem... Gson can see that the type of the field is List statically and deserialize the list based on that.
      3. I had some issues when deserializing Boolean and Integer values from the map, I suspect Object is the issue.
      4. I want to avoid boiler plate code to manually configure type transformers.
      5. I was afraid that I was not seeing something obvious.
      Other Reactions
      1. @ColinD What if List is nested in another class?
      2. custom adapter should implement serializable ?
      3. any help?
      4. @raffian: Do you mean if MyCustomClass has a List field that needs to be deserialized?
      5. It seems that I need to find a way to apply a TypeToken to the TestObject's String[].
      6. I was a bit quick there.
      7. @ColinD I can directly use this 'List list' to populate in android listview?
      8. @ColinD Yes, that's what I mean, a nested List.

    12. Deserializing json array using gson

      You can do this by using the TypeToken class. The idiom used to get listType actually defines an anonymous local inner class containing a method that returns the fully parameterized type. details

      Reactions - Positive 0, Negative 0, Others 0

      1. Type listType = new TypeToken<List<String>>() {}.getType()
      2. gson.toJson(myStrings, listType)
      3. gson.fromJson(json, listType)

    13. GSON: knowing what type of object to convert to?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String response = ...ValueOrError<UserEntity> valueOrError = gson.fromJson(response, new TypeToken<ValueOrError<UserEntity>>(){}.getType())
      2. if (valueOrError.isError()) { ErrorEntity error = valueOrError.getError()
      3. ...} else { UserEntity user = valueOrError.getValue()
      4. ...}

  6. json array in hashmap using google gson

    None .. details

    1. Gson gson = new Gson()
    2. Type listType = new TypeToken<List<HashMap<String, String>>>(){}.getType()
    3. List<HashMap<String, String>> listOfCountry = gson.fromJson(sb.toString(), listType)

    • See Also (18)
    1. How to parse this JSON with GSON?

      Use that to parse your json. Here is a small working example Java 7 This snippet prints the below value key1=[foo1 foo2 foo3 key2=[foo4 foo5 foo6 key3=[foo7 foo8 foo9] . details

      Reactions - Positive 1, Negative 2, Others 0

      1. String json = "{\"key1\": [\"foo1\",\"foo2\",\"foo3\"],\"key2\": [\"foo4\",\"foo5\",\"foo6\"],\"key3\": [\"foo7\",\"foo8\",\"foo9\"]}"
      2. java.lang.reflect.Type type = new TypeToken<Map<String, List<String>>>(){}.getType()
      3. Map<String, List<String>> map = new Gson().fromJson(json, type)
      4. System.out.println(map)

      Positive Reactions
      1. Thank you very much :-).
      Negative Reactions
      1. Your code is working and it showed me where I was wrong.
      2. I had some errors in my code which caused the mentioned exception.
      Other Reactions
      1. But you're right.
      2. Also I had to parse my JSON string to a JsonElement first.
      3. I shouldn't be awake till 7am..

    2. How to Iterate object array [Gson deserialize]?

      You just need to use a TypeToken since List.class doesn't work as you may expect and you cannot do List<SerialDetails>.class. So you need something like . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Type listType = new TypeToken<List<SerialDetails>>() {}.getType()
      2. List<SerialDetails> serialDetails = new Gson().fromJson(sendJsonDataList, listType)
      3. //Now you can iterate over your List...

    3. How to Iterate the JAVA Object LIST made from GSON

      Please help. Use recursion to run over children of EmployeeJSONObj EmployeeJSONObj Output As a side note Use Notepad or other tool to format your Json string. details

      Reactions - Positive 6, Negative 1, Others 0

      1. public class Help {public static void main(String args[]) { String str = "[{" + " \"name\": \"3214657890RootSAPSSE\"," + " \"children\": [{" + " \"name\": \"672BENIAMEEN .Sales Base Market SectionCustomer Representative\"," + " \"children\": [{" + " \"name\": \"672BENIAMEEN .Sales Base Market SectionPeo\"," + " \"children\": [{" + " \"name\": \"910MAZHAR .Sales Base Market SectionCustomer Representative\"," + " \"children\": [{" + " \"name\": \"910MAZHAR .Sales Base Market SectionPeo\"," + " \"children\": [{" + " \"name\": \"713NOSHERWAN .Sales Sargodha SectionCustomer Representative\"," + " \"children\": [{" + " \"name\": \"713NOSHERWAN .Sales Sargodha SectionPeo\"" + " }," + " {" + " \"name\": \"1161SAQLAIN .Sales Toba Taik Singh SecPeo\"" + " }]" + " }]" + " }]" + " }]" + " }," + " {" + " \"name\": \"1161SAQLAIN .Sales Toba Taik Singh SecCustomer Representative\"," + " \"children\": [{" + " \"name\": \"1179SHAMOON .Administration SectionDriver ( R )\"" + " }]" + " }]" + " }," + " {" + " \"name\": \"1179SHAMOON .Farooq Khan TrustDriver ( D)\"" + " }]" + "}]"
      2. System.out.println(str)
      3. Gson gson = new Gson()
      4. Type type = new TypeToken<List<Employees>>(){}.getType()
      5. List<Employees >l = gson.fromJson(str, type)
      6. System.out.println(l)
      7. iterateOverEmployee(l)
      8. }private static void iterateOverEmployee(List<EmployeeJSONObj> l) { for(EmployeeJSONObj emp: l){ if(emp.getChildren() != null){ for(int i=0
      9. i<emp.getChildren().size()
      10. i++) { System.out.println("Name: "+emp.getChildren().get(i).getName()+"<br/>")
      11. } iterateOverEmployee(emp.getChildren())
      12. } }}

      Positive Reactions
      1. Thanks man - I modified your recursive program.
      2. Great thanks.
      3. This is fine but when I change the json string like when I add more child and make it more nested then It is again showing me only 2 childerens.
      4. My json is generating dynamically, and can be upto as many child as many user wants.
      5. AND here is what I am getting from your output [name: 3214657890RootSAPSSE, children [name: 672BENIAMEEN .Sales Base Market SectionCustomer Representative, name: 1179SHAMOON .Farooq Khan TrustDriver ( D)]].
      6. [{"name":"713NOSHERWAN .Sales Sargodha SectionCustomer Representative","children":[{"name":"713NOSHERWAN .Sales Sargodha SectionPeo"},{"name":"1161SAQLAIN .Sales Toba Taik Singh SecPeo"}]}]}]}]},{"name":"1161SAQLAIN .Sales Toba Taik Singh SecCustomer Representative","children":[{"name":"1179SHAMOON .Administration SectionDriver ( R )"}]}]},{"name":"1179SHAMOON .Farooq Khan TrustDriver ( D)"}]}].
      Negative Reactions
      1. It is giving me error bec the list l is of employee type and the function iterateOverEmployee takes list of EmployeeJSONObj.
      Other Reactions
      1. fixed, see my edit, use recursion.
      2. You are a guru of java ;).
      3. ?
      4. [{"name":"3214657890RootSAPSSE","children":[{"name":"672BENIAMEEN .Sales Base Market SectionCustomer Representative","children":[{"name":"672BENIAMEEN .Sales Base Market SectionPeo","children":[{"name":"910MAZHAR .Sales Base Market SectionCustomer Representative","children":[{"name":"910MAZHAR .Sales Base Market SectionPeo","children":.
      5. This is my JSON String I am getting from HTML Hidden field.
      6. I changed my code, try it now, run over all children.
      7. can you post json with more children?
      8. from your code Employees emp l.get(0); we use only 1st child, so ...
      9. ??

    4. jqGrid not displaying the Json data from java

      It produces data that jqGrid can render. . details

      Reactions - Positive 4, Negative 0, Others 0

      1. import java.util.List
      2. public class JQGridContainer { private Integer page
      3. private Integer total
      4. private Integer records
      5. private List<JQGridRow> rows
      6. //getters and setters are omitted for brevity} import java.util.List
      7. public class JQGridRow { private Integer id
      8. private List<String> cell
      9. //getters and setters are omitted for brevity }import java.lang.reflect.InvocationTargetException
      10. import java.util.ArrayList
      11. import java.util.List
      12. import java.util.Set
      13. import org.apache.commons.beanutils.PropertyUtils
      14. import org.apache.commons.lang.ObjectUtils
      15. import org.apache.log4j.Logger
      16. public class JQGridFormatterUtil { private static final Logger logger = Logger .getLogger(JQGridFormatterUtil.class)
      17. public static String getJSON(int currentPageNo, int totalRecords, Set objectsToBeAdded, List orderedPropertyNames) { Integer pages = 0
      18. if(totalRecords % 50 >0){ pages = (totalRecords/50)+1
      19. } else{ pages = (totalRecords/50)
      20. } JQGridContainer container = new JQGridContainer()
      21. container.setPage(currentPageNo)
      22. container.setTotal(pages)
      23. container.setRecords(totalRecords)
      24. List rows = new ArrayList()
      25. if (!objectsToBeAdded.isEmpty()) { for (Object obj : objectsToBeAdded) { JQGridRow row = new JQGridRow()
      26. row.setId(new Integer(getPropertvalue(obj, "id")))
      27. List cells = new ArrayList()
      28. for (String propertyName : orderedPropertyNames) { cells.add(getPropertvalue(obj, propertyName))
      29. } row.setCell(cells)
      30. rows.add(row)
      31. } } container.setRows(rows)
      32. return JSONUtil.convertToJSON(container)
      33. } private static String getPropertvalue(Object bean, String propName) { String val = null
      34. try { val = ObjectUtils.toString(PropertyUtils.getProperty(bean, propName))
      35. } catch (IllegalAccessException e) { logger.error(e)
      36. } catch (InvocationTargetException e) { logger.error(e)
      37. } catch (NoSuchMethodException e) { logger.error(e)
      38. } return val
      39. }import org.apache.log4j.Logger
      40. import com.google.gson.Gson
      41. public class JSONUtil { private static final Logger logger = Logger.getLogger(JSONUtil.class)
      42. public static String convertToJSON(Object obj){ String json = null
      43. Gson gson = new Gson()
      44. json=(gson.toJson(obj))
      45. logger.debug(json)
      46. return json
      47. }}}

      Positive Reactions
      1. JQGrid is smart enough to map it based off the col model.
      2. If the 3rd col doesn't have a value, I'd send in null.
      3. thanks for your answer but i need the answer about what is the problem with my code that cause the jqgrid does not display the data correctly...
      4. I am guessing that it has to do with the col-model having defined 3 values and having only 2 in the json input.
      Other Reactions
      1. Can you post the actual JSON that you get back from the service ?
      2. inside my json rows actually have 3 data,one of it is id...
      3. (This is not the s.o.p output).
      4. I still feel that the col model is the issue.
      5. First, try to remove the cell and just send a json array in "rows".
      6. {"total":1,"page":1,"records":2,"rows":[{"id":1,"cell":["232","12"]},{"id":2," cell":["45","454"]}]}.................this is the output without any arrange...

    5. Unable to parse Json array using Gson

      It should return a List<MapData instead of MapData. Something like I have a fully working example of your issue in this Gist . details

      Reactions - Positive 1, Negative 0, Others 0

      1. public static List<MapData> getData(){ Gson gson = new Gson()
      2. String jsonString = "[{\"id\":18,\"city\":\"test\",\"street\":\"test 1\",\"zipcode\":121209,\"state\":\"IL\",\"lat\":32.158138,\"lng\":34.807838},{\"id\":19,\"city\":\"test\",\"street\":\"1\",\"zipcode\":76812,\"state\":\"IL\",\"lat\":32.161041,\"lng\":34.810410}]"
      3. Type type = new TypeToken<List<MapData>>(){}.getType()
      4. return gson.fromJson(jsonString, type)
      5. }

      Positive Reactions
      1. Thanks, I'll check it and if it works i'll mark it as the right answer.

    6. cant convert json string to regular string array in java

      I suggest you to take a brief look to Gson-documentation it's few lines and you'll understand it better First you serialize your array correctly in your client with Then you send it using Jersey API I think that it's correct although I'm not an expert in Jersey Then your problem is that you are not deserializing the JSON correctly in your web service. You should parse the JSON string passed as a parameter and you can do it with Gson as well like this Now you can do whatever you want with your list of words working with a proper Java List. details

      Reactions - Positive 1, Negative 2, Others 0

      1. Gson gson = new Gson()
      2. Type listOfStringsType = new TypeToken<List<String>>() {}.getType()
      3. List<String> parsedList = gson.fromJson(list, listOfStringsType)

      Positive Reactions
      1. cheers Miko.
      Negative Reactions
      1. ill give it a go.
      2. Just started learning webservices in jersey and its confusing me a quite bit.
      Other Reactions
      1. @eoin see edited answer.
      2. @eoin is my solution working for you?
      3. If not, please comment and I'll try to help...

    7. NullPointerException : JSON Parsing in JAVA using GSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. Type mapOfMapsType = new TypeToken<Map<String, Map<String, Record>>>() {}.getType()
      3. Map<String, Map<String, Record>> map = gson.fromJson(br, mapOfMapsType)

    8. How to get data as an json array from a server and convert it in to java array to use in android application

      In Gson you want to think of them as a Collection of a Collection of Strings. Here's the sample code And the output This is taken from the Google-GSON user guide Examples TOC-Collections Examples . details

      Reactions - Positive 2, Negative 0, Others 0

      1. import java.lang.reflect.Type
      2. import java.util.Collection
      3. import com.google.gson.Gson
      4. import com.google.gson.reflect.TypeToken
      5. public class Main { public static void main(String[] args) { // your sample JSON string, converted to a java string String json = "[\n [\n \"sn1\",\n \"Liquid_level\",\n \"85\"\n ],\n [\n \"sn2\",\n \"Liquid_level,Temperature\",\n \"95\"\n ],\n [\n \"sn2\",\n \"Liquid_level,Temperature\",\n \"50\"\n ],\n [\n \"sn3\",\n \"Liquid_level\",\n \"85.7\"\n ],\n [\n \"sn4\",\n \"Liquid_level\",\n \"90\"\n ],\n [\n \"sn5\",\n \"Volt_meter\",\n \"4.5\"\n ],\n [\n \"sn6\",\n \"Temperature\",\n \"56\"\n ],\n [\n \"sn8\",\n \"Liquid_level\",\n \"30\"\n ]\n]"
      6. // instantiate a Gson object Gson gson = new Gson()
      7. // define the type of object you want to use it in Java, which is a collection of a collection of strings Type collectionType = new TypeToken<Collection<Collection<String>>>(){}.getType()
      8. // happiness starts here Collection<Collection<String>> stringArrays = gson.fromJson(json, collectionType)
      9. // simply print out everything for (Collection<String> collection : stringArrays) { for (String s : collection) { System.out.print(s + ", ")
      10. } System.out.println()
      11. } }}

      Positive Reactions
      1. Thanks Matt Quiros.
      2. You're free to pick a chosen answer if it did any help.
      Other Reactions
      1. :).

    9. Gson - how to parse dynamic JSON string with nested JSON?

      What you call another JSON string is just a json object. Change the Map value type to Object from String TypeToken The above example works with GSON 2.2.2. details

      Reactions - Positive 3, Negative 0, Others 0

      1. String jsonString = "{\"key1\":\"val1\",\"key2\":\"val2\",\"key3\": {\"subkey1\":\"subvalue1\",\"subkey2\":\"subvalue2\"},\"key4\":\"val3\"}"
      2. Map<String, Object> map = new Gson().fromJson(jsonString, new TypeToken<Map<String, Object>>() {}.getType())

      Positive Reactions
      1. For example you could create some recursive method that prints out a value if it is a string or iterates over the values if it is a Map and recursively calls itself for every one of them.If you consider this question answered, could you accept it please?
      2. I loop through parsed Objects in Map and I am processing them - is there some way how to solve out if Object is another Map and not string value?
      3. Yes, now it works, thank you.
      Other Reactions
      1. The question is what you want to do with it.
      2. It doesn't work with this JSON: {"key1":"val1","key2":"val2","key3":{"subkey1" :["subvalue1","subvalue1"],"subkey2":["subvalue2"]},"key4":"val3"} created by this PHP code (notice that subkey1 and subkey2 is an array and not a single value as before): $foo array();$foo["key1"] 'val1';$foo["key2"] 'val2';$foo["key3"] array('subkey1'=>array('subvalue1','subvalue1'),'subkey2 '=>array('subvalue2'));$foo["key4"] 'val3';var_dump(json_encode($foo)); "doesn't work" mean that this nested JSON object is not parsed and is returned as a String.
      3. @user1315357 There are obviously ways to solve it.
      4. You can test if a _value_ is a _Map_ using the _instanceof_ parameter.

    10. JSON to Java Object

      This worked.The in PhotoDTO[ was what I was missing. Another option without creating DTOs using Gson class StringMap EDIT Imports . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String json = "[ { \"url\" : \"/photos/avatar-1.jpg\" , \"photo\" : \"avatar-1.jpg\" , \"description\" : \"test 1\"} , { \"url\" : \"/photos/avatar-2.jpg\" , \"photo\" : \"avatar-2.jpg\" , \"description\" : \"test 2\"} , { \"url\" : \"/photos/avatar-3.jpg\" , \"photo\" : \"avatar-3.jpg\" , \"description\" : \"test 3\"} , { \"url\" : \"/photos/avatar-4.jpg\" , \"photo\" : \"avatar-4.jpg\" , \"description\" : \"test 4\"}]"
      2. Gson gson = new Gson()
      3. Type type = new TypeToken<List<StringMap<String>>>(){}.getType()
      4. List<StringMap<String>> stringMaps = gson.fromJson(json, type)
      5. for (StringMap<String> map:stringMaps) { System.out.println(map.get("photo"))
      6. }

    11. Json to Map

      how to get value1 from your gson . Use the following code Utilize the libraries com.google.gson.Gson com.google.common.reflect.TypeToken and java.lang.reclect.Type . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Type mapType = new TypeToken<Map<String, Map>>(){}.getType()
      2. Map<String, String[]> son = new Gson().fromJson(easyString, mapType)

    12. Getting a typed ArrayList from a JSON String in Java

      That somebody who has 17.2k rep does not understand something so fundamental is truly worrying. From the Collections-Examples docs you don't supply ArrayList.class as parameter you specify the type the list contains by using a TypeToken and passing that to fromJSON . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. Type collectionType = new TypeToken<Collection<Integer>>(){}.getType()
      3. //change this to whatever type you json containsCollection<Integer> ints2 = gson.fromJson(br, collectionType)

    13. Comparing two JSONs

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Type type = new TypeToken<Map<String, String>>() {}.getType()
      2. Gson gson = new Gson()
      3. Map<String, String> mapExpected = gson.fromJson(expectedJson, type)
      4. Map<String, String> mapResponse = gson.fromJson(jsonResponse, type)
      5. Set<SimpleEntry<String,String>> expectedSet = new HashSet<SimpleEntry<String, String>>()
      6. Set<SimpleEntry<String, String>> tmpExpectedSet = new HashSet<SimpleEntry<String, String>>()
      7. Set<SimpleEntry<String, String>> responseSet = new HashSet<SimpleEntry<String, String>>()
      8. for (String key : mapExpected.keySet()) { expectedSet.add(new SimpleEntry<String, String>(key, mapExpected.get(key)))
      9. tmpExpectedSet.add(new SimpleEntry<String, String>(key, mapExpected.get(key)))
      10. } for (String key : mapResponse.keySet()) responseSet.add((new SimpleEntry<String, String>(key, mapResponse.get(key))))
      11. expectedSet.removeAll(responseSet)
      12. responseSet.removeAll(tmpExpectedSet)
      13. expectedSet.addAll(responseSet)
      14. if (!expectedSet.isEmpty()) { for (SimpleEntry<String, String> diff : expectedSet) log.error(diff.getKey() + ":" + diff.getValue())
      15. }

    14. How to put a List<class> into a JSONObject and then read that object?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Type collectionType = new TypeToken<List<Class>>() { } // end new .getType()
      2. String gsonString = new Gson().toJson(objList, collectionType)

    15. Parse JSON string to Dictionary<String, Integer> with Gson

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // input: {"altruism":1,"amazon":6}String jsonInput = "{\"altruism\":1,\"amazon\":6}"
      2. Map<String, Integer> map = new Gson().fromJson(jsonInput, new TypeToken<HashMap<String, Integer>>() {}.getType())
      3. System.out.println(map)
      4. // {altruism=1, amazon=6}System.out.println(map.getClass())
      5. // class java.util.HashMapSystem.out.println(map.keySet().iterator().next().getClass())
      6. // class java.lang.StringSystem.out.println(map.get("altruism").getClass())
      7. // class java.lang.Integer

    16. JSONArray to string array

      It's got a much friendlier API than org.json. Collections-Examples from the user-guide User-Guide . details

      Reactions - Positive 2, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. Collection<Integer> ints = Lists.immutableList(1,2,3,4,5)
      3. //(Serialization)String json = gson.toJson(ints)
      4. ==> json is [1,2,3,4,5]//(Deserialization)Type collectionType = new TypeToken<Collection<Integer>>(){}.getType()
      5. Collection<Integer> ints2 = gson.fromJson(json, collectionType)
      6. //ints2 is same as ints

      Positive Reactions
      1. int[] ints2 gson.fromJson("[1,2,3,4,5]", int[].class); something like this is what I was looking for.
      2. Thanks.

    17. Reading JSon String with Gson

      Here's how you can convert it. A01 A02 etc become Map keys and its value becomes the Event value of Map. details

      Reactions - Positive 0, Negative 0, Others 0

      1. Map<String, Event> events = new Gson().fromJson(json, new TypeToken<Map<String, Event>>(){}.getType())

    18. Library to encode/decode from json to java.util.Map?

      It has excellent support for guide#TOC-Serializing-and-Deserializing-Gener Generic-types . Here's an SSCCE . details

      Reactions - Positive 5, Negative 1, Others 0

      1. package com.stackoverflow.q2496494
      2. import java.util.LinkedHashMap
      3. import java.util.Map
      4. import com.google.gson.Gson
      5. import com.google.gson.reflect.TypeToken
      6. public class Test { public static void main(String... args) { Map<String, String> map = new LinkedHashMap<String, String>()
      7. map.put("key1", "value1")
      8. map.put("key2", "value2")
      9. map.put("key3", "value3")
      10. Gson gson = new Gson()
      11. // Serialize. String json = gson.toJson(map)
      12. System.out.println(json)
      13. // {"key1":"value1","key2":"value2","key3":"value3"} // Deserialize. Map<String, String> map2 = gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType())
      14. System.out.println(map2)
      15. // {key1=value1, key2=value2, key3=value3} }}

      Positive Reactions
      1. Gson can handle it perfectly as well.
      2. Awesome answer.
      3. Or, more OO-friendly, just use a fullworthy Javabean.
      4. Thank you.
      5. The reason I suggest Jackson is by the way because it is fast**.
      Negative Reactions
      1. I've totally missed the TypeToken class, and could't remember what I did wrong.
      Other Reactions
      1. Either replace Map by Map or Map.
      2. The problem is I'm using an environment that doesn't support generics, ( erhmm.
      3. :).
      4. Else Gson won't run at any way.
      5. Is there a way to decode ( deserialize ) to non generic map ?
      6. You may consider to have a look at Jackson then: URL_http://jackson.codehaus.org / (tutorial here URL_http://jackson.codehaus.org/Tutorial , Ctrl+F on "untyped" to achieve the same what you want).
      7. don't ask me how or why, I just, can't use them ) and what I'm trying to find is a way to convert plain lists of maps to json and have them back.
      8. See this answer for an example: URL_http://stackoverflow.com/questions/1688099/converting-json-to - java/1688182#1688182.
      9. I see.
      10. Benchmarks here BTW: URL_http://www.cowtowncoder.com/blog/archives/2009/02/entry_204.html .
      11. +1 ...15 chars.
      12. Does it run Java 1.5 at any way?

  7. Convert from JSon to multiple unknown java object types using GSon

    Accepting answer. Create model class Create subclass call parseGson Method gson parse method with object class You can set global variables that cast to myModel . .. details

    1. public void parseGson(Object object){ object = gson.fromJson(response.toString(), object.getClass())
    2. SubClass subclass = (SubClass)object
    3. }

    • See Also (4)
    1. Gson Generics attribute

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class LoadJson<T> {
      2. Response<T> load(String responseElement, Type classType) {
      3. Gson gson = new Gson()
      4. Response<T> response = gson.fromJson(responseElement, classType)
      5. return response
      6. }
      7. }

    2. Gson: can we get the serialized field name in a type adapter?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Exception in thread "main" GsonEnumParsinException [notFoundEnumValue=RED, enumName=stackoverflow.questions.q16715117.Colour, fieldName=colour] at stackoverflow.questions.q16715117.Q16715117$CustomEnumTypeAdapter.read(Q16715117.java:90) at stackoverflow.questions.q16715117.Q16715117$CustomEnumTypeAdapter.read(Q16715117.java:1) at stackoverflow.questions.q16715117.CustomReflectiveTypeAdapterFactory$1.read(CustomReflectiveTypeAdapterFactory.java:79) at stackoverflow.questions.q16715117.CustomReflectiveTypeAdapterFactory$Adapter.read(CustomReflectiveTypeAdapterFactory.java:162) at com.google.gson.Gson.fromJson(Gson.java:803) at com.google.gson.Gson.fromJson(Gson.java:768) at com.google.gson.Gson.fromJson(Gson.java:717) at com.google.gson.Gson.fromJson(Gson.java:689) at stackoverflow.questions.q16715117.Q16715117.main(Q16715117.java:35)

    3. Gson: can we get the serialized field name in a type adapter?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Exception in thread "main" GsonEnumParsinException [notFoundEnumValue=RED, enumName=stackoverflow.questions.q16715117.Colour] at stackoverflow.questions.q16715117.Q16715117$CustomEnumTypeAdapter.read(Q16715117.java:77) at stackoverflow.questions.q16715117.Q16715117$CustomEnumTypeAdapter.read(Q16715117.java:1) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172) at com.google.gson.Gson.fromJson(Gson.java:803) at com.google.gson.Gson.fromJson(Gson.java:768) at com.google.gson.Gson.fromJson(Gson.java:717) at com.google.gson.Gson.fromJson(Gson.java:689) at stackoverflow.questions.q16715117.Q16715117.main(Q16715117.java:22)

    4. Parsing generic tag in JSON from GSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. AllShowsActivityData obj = gson.fromJson(reader, AllShowsActivityData.class)

  8. How to display Json object in jsp

    None .. details

    1. $(document).ready(function() { var table = $('<table/>').appendTo($('#somediv'))
    2. $.getJSON('url/to/servlet', function(persons) { persons.each(function(i, person) { $('<tr/>').appendTo(table) .append($('<td/>').text(person.name)) .append($('<td/>').text(person.address))
    3. })
    4. })
    5. })

    • See Also (6)
    1. How to deserialize generic object from file in Json format

      Due to compile-time-type-erasure your generic parameter T doesn't exist at run time. As you correctly point out you cannot do T.class as there is no T In order to do what you want you need to request an instance of the Class object corresponding to your type parameter be passed into the method That way you can use the type variable to pass into the Gson method . details

      Reactions - Positive 0, Negative 0, Others 0

      1. return gson.fromJson(reader, type)

      Other Reactions
      1. The whole point is to make a class responsible to know what class of object to return and do this stuff withoug class casting...
      2. Can I do that with TypeToken?
      3. @user1685095 you can't do that with generics because they don't exist at run time.

    2. play framework 2.0 json - receiving null JsonNode object

      The expected result of the ajax call is a json object. In this case if you want to response with a plain text add dataType text' to the request . details

      Reactions - Positive 2, Negative 1, Others 0

      1. jsRoutes.controllers.Application.receiveData().ajax({ data:outputData, dataType: 'text', contentType:'application/json', success: function(data) { console.log(data)
      2. }, error: function() { alert("Error!")
      3. } })

      Positive Reactions
      1. I tried with POST as well but same result.
      2. Thanks.
      Negative Reactions
      1. Ah ok, now I see the problem.
      Other Reactions
      1. Setting the type to text worked.
      2. I edit the answer.

    3. JQuery post JSON object to a server

      UPDATE This is how you would structure the ajax request to send the json as a post var. The json will now be in the json post var. details

      Reactions - Positive 1, Negative 0, Others 0

      1. function sendData() { $.ajax({ url: '/helloworld', type: 'POST', contentType: 'application/json', data: { json: JSON.stringify({ name:"Bob", ... })}, dataType: 'json' })
      2. alert("json posted!")
      3. }
      4. }

      Positive Reactions
      1. Thank you!
      Other Reactions
      1. When sent in this way, the json will be the request body.
      2. I'm still figuring out how the server get the json object.
      3. Suppose I have JSONObject created using jsp and want to pass to next page then how to send JSONObject (jsonobj) in jquery POST.
      4. i.e.
      5. If you instead want the json to be in a POST var, the ajax request will need to be modified.
      6. @Optimus both ways do send the jsonobject in a post request.
      7. With the first, the jsonstring will be in the request body of the post request, and the second the jsonstring will be in a post variable named "json".
      8. But what if I want to Json object as it.

    4. JQuery post JSON object to a server

      To send json to the server you first have to create json then you have to tell jQuery not to alter that json. UPDATE This is how you would structure the ajax request to send the json as a post var. details

      Reactions - Positive 1, Negative 0, Others 0

      1. function sendData() { $.ajax({ url: '/helloworld', type: 'POST', contentType: 'application/json', data: JSON.stringify({ name:"Bob", ... }), processData: false, dataType: 'json' })
      2. alert("json posted!")
      3. }
      4. }

      Positive Reactions
      1. Thank you!
      Other Reactions
      1. When sent in this way, the json will be the request body.
      2. I'm still figuring out how the server get the json object.
      3. Suppose I have JSONObject created using jsp and want to pass to next page then how to send JSONObject (jsonobj) in jquery POST.
      4. i.e.
      5. If you instead want the json to be in a POST var, the ajax request will need to be modified.
      6. @Optimus both ways do send the jsonobject in a post request.
      7. With the first, the jsonstring will be in the request body of the post request, and the second the jsonstring will be in a post variable named "json".
      8. But what if I want to Json object as it.

    5. json Deserializer in to target object

      In particular see the Object-Examples . The only catch here but you will have this same problem with any other JSON de)serializer is the nonstandard deep object format you want to work with. details

      Reactions - Positive 2, Negative 0, Others 0

      1. class BagOfPrimitives { private int value1 = 1
      2. private String value2 = "abc"
      3. private transient int value3 = 3
      4. BagOfPrimitives() { // no-args constructor }}BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class)

      Positive Reactions
      1. Thanks, but where is the merge here?
      2. Write a custom method on the Affiliate object, something like Affiliate#mergeWith(Affiliate other).
      Other Reactions
      1. I don't think you're going to find a JSON library that does this for you.
      2. I want to merge the object with an existing object.
      3. see my code again mayby, Thanks.

    6. JSON formatting (Sending JSON via jQuery AJAX post to Java/Wicket server)

      Thanks. You have to use JSON.stringify You should also specify application/json as the contentType. details

      Reactions - Positive 5, Negative 4, Others 0

      1. $.ajax({ type: 'post', data: JSON.stringify(lookup), contentType: 'application/json', dataType: 'json'})

      Positive Reactions
      1. If lookup is {foo: "bar"}, that will be url-encoded to something like lookup=%7B%22foo%22%3A%22bar%22%7D That obviously isn't a valid JSON document.
      2. Thanks!.
      3. Ah, excellent explanation!
      4. Also, if you want your data to come back as a parameter value and not a key, send it like this: data: {'lookup': JSON.stringify(lookup)}.
      5. Thanks for catching that!
      Negative Reactions
      1. I did need to stringify my JSON, though, which solved my problem.
      2. Note: If you get a "JSON is undefined" error (IE6/7) you'll need to include json.org's latest json.js file in your page.
      3. And {'lookup': JSON.stringify(lookup)} isn't quite correct.
      4. Method is ignored, and the default is GET.
      Other Reactions
      1. dataType specifies what you expect the server to send.
      2. When you're posting application/json, you don't use url-encoding.
      3. It should be type: 'post'.
      4. @Jared, no.
      5. contentType is the content type you're sending, and jQuery will not change it based on dataType.
      6. I think this might be connected to you putting method: 'post'.
      7. jQuery automatically adds the content type as application/json when you specify the dataType as json, doesn't it?

  9. How to get JSON element type with Gson?

    I wrote this simple class that shows you how use some Gson classes to get what you need. And this is the result with your JSON string JSON has a recursive nature so the only way to approach to this kind of problem is to write a recursive method. .. details

    1. package stackoverflow.questions.q19124387
    2. import com.google.gson.*
    3. import java.util.Map
    4. public class Q20624042 {
    5. private static String printClass(JsonElement je, String ident) {
    6. StringBuilder sb = null
    7. if (je.isJsonNull()) return "null"
    8. if (je.isJsonPrimitive()) {
    9. if (je.getAsJsonPrimitive().isBoolean()) return "Boolean"
    10. if (je.getAsJsonPrimitive().isString()) return "String"
    11. if (je.getAsJsonPrimitive().isNumber()) {
    12. return "Number"
    13. }
    14. }
    15. if (je.isJsonArray()) {
    16. sb = new StringBuilder("array<")
    17. for (JsonElement e : je.getAsJsonArray()) {
    18. sb.append(printClass(e, ident + " "))
    19. }
    20. sb.append(">")
    21. return sb.toString()
    22. }
    23. if (je.isJsonObject()) {
    24. sb = new StringBuilder("map<\n")
    25. for (Map.Entry<String, JsonElement> e : je.getAsJsonObject().entrySet()) {
    26. sb.append(ident)
    27. sb.append(e.getKey()).append(":")
    28. sb.append(printClass(e.getValue(), ident + " "))
    29. sb.append("\n")
    30. }
    31. sb.append(ident)
    32. sb.append(">")
    33. return sb.toString()
    34. }
    35. return ""
    36. }
    37. public static void main(String[] args) {
    38. String json =
    39. "{"
    40. + "\"number\":1,"
    41. + "\"ts\":\"1386848002\","
    42. + "\"cmpg\":[{\"id\":476,\"mcp\":0.0000,\"deals\":[],\"cookie\":\"uid:123\",\"bid\":[{\"bId\":0,\"status\":\"ZB\",\"rmtchID\":-1}]}]}"
    43. JsonElement je = new JsonParser().parse(json)
    44. System.out.println(printClass(je, " "))
    45. }
    46. }

  10. Read json from string in java

    This question has been answered so often that you actively need to turn the other way when SO proposes you the related questions. Using Gson and one of Gson#fromJson methods gson/Gson.html#fromJson%28java.lang.String,%20java.lang.Class%29 fromJson(String,-Class) gson/Gson.html#fromJson%28java.io.Reader,%20java.lang.Class%29 fromJson(Reader,-Class) Simple example Define the class(s you want to map the json data to Now Test with the following Json String This prints see the javadoc of the class gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html Gson for other alternatives. .. details

    1. YourType o = new Gson().fromJson(new StringReader("your json string"), YourType.class)

    Positive Reactions
    1. Please see the user guide I have linked to.
    Other Reactions
    1. @amrutha it is the tpye you want to convert the json String to, a class that you have to create.
    2. wt is YourType here.
    3. Can any one help me to consume and produce a json using restful webservice.
    4. @amrutha, I have added a small example, see my edit.

  11. Read json from string in java

    None .. details

    1. @Testpublic void fromJson() { Person o = new Gson().fromJson( "{\r\n" + " \"firstName\":\"John\",\r\n" + " \"lastName\":\"Doe\",\r\n" + " \"age\":24,\r\n" + " \"hobbies\":[\r\n" + " {\r\n" + " \"name\":\"Programming\"\r\n" + " },\r\n" + " {\r\n" + " \"name\":\"Sports\"\r\n" + " }\r\n" + " ]\r\n" + "}", Person.class)
    2. System.out.println(o.toString())
    3. }

  12. GSON parsing fromJSON regarding arrays of objects exception

    So I suggest you to make a file for each class or use only static inner classes. To respond to your question note that I changed your Visualization class with Trace traces since you have only a Trace object in your JSON and not an array. .. details

    1. package stackoverflow.questions
    2. import java.util.*
    3. import com.google.gson.Gson
    4. public class Q20461706 { public class Trace { ArrayList<Message> messages
    5. ArrayList<Scenario> scenarios
    6. @Override public String toString() { return "Trace [messages=" + messages + ", scenarios=" + scenarios + "]"
    7. } } public static class Message { String from
    8. // "from": "dudu", String method
    9. // "method": "call()", String scenario
    10. // "scenario": "#1", String timestamp
    11. // "timestamp": "09-12-2013 00:21:14", String to
    12. // "to": "dudu", String type
    13. // "type": "void", Boolean violation
    14. // "violation": "true", Boolean visible
    15. // "visible": "true" @Override public String toString() { return "Message [from=" + from + ", method=" + method + ", scenario=" + scenario + ", timestamp=" + timestamp + ", to=" + to + ", type=" + type + ", violation=" + violation + ", visible=" + visible + "]"
    16. } } public static class Scenario { String name
    17. // "name": "testscenario", String id
    18. // "id": "#1", String description
    19. // "description": "testing parsing!" @Override public String toString() { return "Scenario [name=" + name + ", id=" + id + ", description=" + description + "]"
    20. } } public static class Component { String fullname
    21. // "fullname": "CC/dudu", String name
    22. // "name": "dudu", String type
    23. // "type": "String", List<Component> children
    24. @Override public String toString() { return "Component [fullname=" + fullname + ", name=" + name + ", type=" + type + ", children=" + children + "]"
    25. } } public static class Visualization { Component root
    26. Trace traces
    27. @Override public String toString() { return "Visualization [root=" + root + ", traces=" + traces + "]"
    28. } } public static class Response { Visualization visualization
    29. @Override public String toString() { return "Response [visualization=" + visualization + "]"
    30. } } public static void main(String[] args) { String json = " {\"visualization\": { "+ " \"root\": { "+ " \"fullname\": \"CC/dudu\", "+ " \"name\": \"dudu\", "+ " \"type\": \"String\", "+ " \"children\": [ "+ " { "+ " \"fullname\": \"CC/dudu/lulu\", "+ " \"name\": \"lulu\", "+ " \"type\": \"String\" "+ " } "+ " ] "+ " }, "+ " \"traces\": { "+ " \"messages\": [ "+ " { "+ " \"from\": \"dudu\", "+ " \"method\": \"call()\", "+ " \"scenario\": \"#1\", "+ " \"timestamp\": \"09-12-2013 00:21:14\", "+ " \"to\": \"dudu\", "+ " \"type\": \"void\", "+ " \"violation\": \"true\", "+ " \"visible\": \"true\" "+ " } "+ " ], "+ " \"scenarios\": [ "+ " { "+ " \"name\": \"testscenario\", "+ " \"id\": \"#1\", "+ " \"description\": \"testing parsing!\" "+ " } "+ " ] "+ " } "+ " }} "
    31. Gson gsonParser = new Gson()
    32. Response r = gsonParser.fromJson(json, Response.class)
    33. System.out.println(r)
    34. }}

    Negative Reactions
    1. Malformed in the sense that it was not the JSON I wanted, yet it somehow was a valid JSON representation.
    2. It indeed parses the code, however, my previous problem was a malformed JSON.
    3. I merely posted them like that to increase readability.
    Other Reactions
    1. Also, note, NOT all of my classes where IN ONE FILE.

    • See Also (10)
    1. Generating a JSON doc with envelope/header using Gson

      You can run directly this example. and this is the result To see it formatted like your example you need an external formatter like this . details

      Reactions - Positive 2, Negative 1, Others 0

      1. package stackoverflow.questions.q19966529
      2. import com.google.gson.Gson
      3. import java.util.*
      4. public class Q19966529 {
      5. public static class User {
      6. Long userId
      7. String userName
      8. String displayName
      9. public User(Long userId, String userName, String displayName) {
      10. this.userId = userId
      11. this.userName = userName
      12. this.displayName = displayName
      13. }
      14. }
      15. public static class UserList {
      16. private List<User> list = new ArrayList<>()
      17. //java 7 private int count = 0
      18. public void addUser(User u) {
      19. list.add(u)
      20. count = list.size()
      21. }
      22. }
      23. public static void main(String[] args) {
      24. UserList ul = new UserList()
      25. ul.addUser(new User(149L, "jack0231", "Jackie"))
      26. ul.addUser(new User(301L, "helms_mighty", "Hippoman"))
      27. String json = new Gson().toJson(ul)
      28. System.out.println(json)
      29. }
      30. }

      Positive Reactions
      1. Thanks very much for posting an answer!.
      2. I guess that works.
      Negative Reactions
      1. Ugh.
      Other Reactions
      1. Your answer would work, so I'll accept it as the answer.
      2. Maybe I should subclass Gson, that would work too.

    2. JSON Parsing using minimal-json and Gson

      ). My solution This is the execution You should always let Gson do the work for you. details

      Reactions - Positive 2, Negative 0, Others 0

      1. public static void main(String[] args) { String json = "[ { \"season\":1, \"episode\":1, \"number\":1, \"tvdb_id\":2493011, \"title\":\"Days Gone Bye\", \"overview\":\"Rick searches for his family after emerging from a coma into a world terrorized by the walking dead. Morgan and Duane, whom he meets along the way, help teach Rick the new rules for survival.\", \"first_aired\":1288584000, \"first_aired_iso\":\"2010-10-31T21:00:00-05:00\", \"first_aired_utc\":1288598400, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/1\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-1.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-1.22.jpg\" }, \"ratings\":{ \"percentage\":89, \"votes\":763, \"loved\":733, \"hated\":30 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":false, \"rating_advanced\":0 }, { \"season\":1, \"episode\":2, \"number\":2, \"tvdb_id\":2493181, \"title\":\"Guts\", \"overview\":\"Rick unknowingly causes a group of survivors to be trapped by walkers. The group dynamic devolves from accusations to violence, as Rick must confront an enemy far more dangerous than the undead.\", \"first_aired\":1289192400, \"first_aired_iso\":\"2010-11-07T21:00:00-06:00\", \"first_aired_utc\":1289210400, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/2\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-2.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-2.22.jpg\" }, \"ratings\":{ \"percentage\":87, \"votes\":533, \"loved\":507, \"hated\":26 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":false, \"rating_advanced\":0 }, { \"season\":1, \"episode\":3, \"number\":3, \"tvdb_id\":2656081, \"title\":\"Tell It to the Frogs\", \"overview\":\"After returning to the camp with the department store survivors and an emotional reunion with his wife and son, Rick decides to go against Shane's advice and go back to Atlanta for Merle Dixon and his dropped bag of guns accompanied by Merle's younger brother, Darryl Dixon, as well as Glenn and T-Dog.\", \"first_aired\":1289797200, \"first_aired_iso\":\"2010-11-14T21:00:00-06:00\", \"first_aired_utc\":1289815200, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/3\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-3.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-3.22.jpg\" }, \"ratings\":{ \"percentage\":85, \"votes\":484, \"loved\":458, \"hated\":26 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":false, \"rating_advanced\":0 }, { \"season\":1, \"episode\":4, \"number\":4, \"tvdb_id\":2656091, \"title\":\"Vatos\", \"overview\":\"While still in search of Merle, the group tries to retrieve the bag of guns but are attacked by several living men who are also after the weapons. The group manages to grab the injured attacker
      2. however, several of the attackers escape and take Glenn hostage. Back at camp a large group of walkers venture up the hill and take the survivors by surprise.\", \"first_aired\":1290402000, \"first_aired_iso\":\"2010-11-21T21:00:00-06:00\", \"first_aired_utc\":1290420000, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/4\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-4.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-4.22.jpg\" }, \"ratings\":{ \"percentage\":88, \"votes\":490, \"loved\":467, \"hated\":23 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":false, \"rating_advanced\":0 }, { \"season\":1, \"episode\":5, \"number\":5, \"tvdb_id\":2656101, \"title\":\"Wildfire\", \"overview\":\"Rick leads the group to the CDC after the attack on the camp. Jim must make a terrible life and death decision.\", \"first_aired\":1291006800, \"first_aired_iso\":\"2010-11-28T21:00:00-06:00\", \"first_aired_utc\":1291024800, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/5\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-5.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-5.22.jpg\" }, \"ratings\":{ \"percentage\":87, \"votes\":460, \"loved\":443, \"hated\":17 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":\"love\", \"rating_advanced\":10 }, { \"season\":1, \"episode\":6, \"number\":6, \"tvdb_id\":2656111, \"title\":\"TS-19\", \"overview\":\"Rick and the group are allowed into the CDC by a strange doctor, but all is not what it seems in their newfound haven. \", \"first_aired\":1291611600, \"first_aired_iso\":\"2010-12-05T21:00:00-06:00\", \"first_aired_utc\":1291629600, \"url\":\"http://trakt.tv/show/the-walking-dead/season/1/episode/6\", \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-6.22.jpg\", \"images\":{ \"screen\":\"http://slurm.trakt.us/images/episodes/124-1-6.22.jpg\" }, \"ratings\":{ \"percentage\":87, \"votes\":465, \"loved\":440, \"hated\":25 }, \"watched\":true, \"in_collection\":true, \"in_watchlist\":false, \"rating\":\"love\", \"rating_advanced\":10 } ]"
      3. ArrayList<Map> al = new Gson().fromJson(json, ArrayList.class)
      4. for(Map m : al){ System.out.printf("Ep. %.0f aired on %s\n", m.get("episode"), m.get("first_aired_iso"))
      5. }}

      Positive Reactions
      1. Thank you for you comment, but tell me, where do you find complexity?
      2. Found this slightly more complicated than the one that worked for me.But still, nice solution, definitely cleaner than mine.
      Other Reactions
      1. :).

    3. How to Iterate object array [Gson deserialize]?

      So you need something like . issue corrected i'm mistakenly used object arraylist instead for objectarray now its works perfect thanks for all . details

      Reactions - Positive 1, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. List<SerialDetails> serialDetails =new ArrayList<SerialDetails>()
      3. SerialDetails[] serialDetailsRecords = gson.fromJson(sendJsonDataList, SerialDetails[].class)
      4. for (SerialDetails item: serialDetailsRecords) { item.toString()
      5. }

      Positive Reactions
      1. Please, since you solved, mark your question as answer and don't forget to check @MikO advice.

    4. Gson Json parser Array of Arrays

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static void main(String args[]) { Gson gson = new Gson()
      2. String jsonstr ="{ \"type\": \"MultiPolygon\",\"coordinates\": [ [ [ [ -71.25, 42.33 ], [ -71.25, 42.33 ] ] ], [ [ [ -71.23, 42.33 ], [ -71.23, 42.33 ] ] ] ]}"
      3. JsonObjectBreakDown obj = gson.fromJson(jsonstr, JsonObjectBreakDown.class)
      4. System.out.println(Arrays.toString(obj.coordinates.get(0).get(0).get(0)))
      5. }public static class JsonObjectBreakDown { public String type
      6. public List<List<List<String[]>>> coordinates = new ArrayList<>()
      7. public void setCoordinates(List<List<List<String[]>>> coordinates) { this.coordinates = coordinates
      8. }}

    5. serializing java object to json with auto generated names

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.common.collect.Lists
      2. import com.google.gson.Gson
      3. import java.util.ArrayList
      4. import java.util.LinkedHashMap
      5. import java.util.List
      6. import java.util.Map
      7. public class Test {
      8. public static class User {
      9. private List<Integer> ids
      10. private List<String> names
      11. public User(List<Integer> ids, List<String> names) {
      12. this.ids = ids
      13. this.names = names
      14. }
      15. }
      16. public static void main(String[] args) {
      17. List<User> users = new ArrayList<User>()
      18. users.add(
      19. new User(Lists.newArrayList(1, 2, 3), Lists.newArrayList("anton", "berta", "charlie")))
      20. users.add(
      21. new User(Lists.newArrayList(4, 5, 6), Lists.newArrayList("dora", "emil", "friedrich")))
      22. Map<String, User> map = new LinkedHashMap<String, User>()
      23. for (int i = 0 i < users.size() i++) {
      24. map.put(String.valueOf(i + 1), users.get(i))
      25. }
      26. System.out.printf(new Gson().toJson(map))
      27. }
      28. }

    6. Gson Custom Serializer Not Called

      You might want to verify that your specification array is not empty in each of those items you're printing. Of course I can't directly copy the code in as I've gotten rid of it and I wasn't yet to the point where I'd start versioning but essentially Setting i to the returned Item didn't really work and so then when I tried to serialize the HashMap in my objects wasn't set properly as Perception noted. details

      Reactions - Positive 0, Negative 0, Others 0

      1. ArrayList<Item> items = new ArrayList<Item>()
      2. Gson gson = new Gsonfor (Item i : items){ i.setId(something)
      3. }for (Item i : items){ //... //send query and get response here //... i = gson.fromJson(in, Item.class)
      4. }

    7. deserializing a JSON object with multiple items inside it

      One solution to parsing it is to utilize a JSONObject directly. The data can also be viewed as a map of id's to attachments. details

      Reactions - Positive 1, Negative 2, Others 0

      1. String json = ...
      2. final Gson gson = new Gson()
      3. final List<Attachment> attachements = new ArrayList<Attachment>(64)
      4. final JSONObject jsonObj = new JSONObject(json).getJSONObject("attachments")
      5. final Iterator<String> keys = jsonObj.keys()
      6. while(keys.hasNext()) { final String key = keys.next()
      7. attachements.add(gson.fromJson(jsonObj.getJSONObject(key).toString(), Attachment.class)
      8. }// Do something with attachements

      Positive Reactions
      1. thanks.
      Negative Reactions
      1. I think there is a misunderstanding here, either on my part or yours.
      2. had to do a little extra work, but your solution got me there.
      Other Reactions
      1. What is being represented here are not articles, but components of articles (namely attachments) which I'm trying to deserialize into fields of the Article instances you helped me with before..
      2. That's what I figured :) I'm trying what you suggested but am getting an error warning - Can only iterate over an array or an instance of java.lang.Iterable - on the for loop.
      3. see my edit if you're curious.
      4. Check out my edit (nothing substantial, basically replace Article with Attachment).
      5. You might have to tweak the code, I don't have access to an IDE atm.
      6. @drewmore4 - edited.
      7. @drewmore4 - indeed.

    8. how to prepare json file using gson library

      Here's such an example. If it's not possible to have a Java class structure that matches the target JSON structure and you're stuck with only the original classes then you can use a oogle/gson/stream/JsonWriter.html JsonWriter to build the JSON one token at a time. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. import java.util.ArrayList
      3. import java.util.List
      4. public class Foo {
      5. public static void main(String[] args) {
      6. Person person = new Person("name1", 1)
      7. List<Person> personList = new ArrayList<Person>(1)
      8. personList.add(person)
      9. Address address = new Address("home1", "office1")
      10. Thing thing = new Thing(personList, address)
      11. Gson gson = new Gson()
      12. String json = gson.toJson(thing)
      13. System.out.println(json)
      14. }
      15. }
      16. class Thing {
      17. private List<Person> person
      18. private Address address
      19. Thing(List<Person> person, Address address) {
      20. this.person = person
      21. this.address = address
      22. }
      23. }
      24. class Person {
      25. private String name
      26. private int id
      27. Person(String name, int id) {
      28. this.name = name
      29. this.id = id
      30. }
      31. }
      32. class Address {
      33. private String homeaddress
      34. private String officeaddress
      35. Address(String homeaddress, String officeaddress) {
      36. this.homeaddress = homeaddress
      37. this.officeaddress = officeaddress
      38. }
      39. }

    9. How do I create a multidimensional HashMap or Hashtable in JSP / Java and convert it to a JSON object?

      So to achieve the following JSON format you need a deep breathe Map<String List<Map<String List<Map<String String. Better is to just use fullworthy Javabeans instead of Map<String String. details

      Reactions - Positive 8, Negative 0, Others 0

      1. List<Map<String, String>> addressComponents = new ArrayList<Map<String, String>>()
      2. Map<String, String> addressComponent1 = new HashMap<String, String>()
      3. addressComponent1.put("long_name", "1600")
      4. addressComponent1.put("short_name", "1600")
      5. addressComponents.add(addressComponent1)
      6. Map<String, String> addressComponent2 = new HashMap<String, String>()
      7. addressComponent2.put("long_name", "Amphitheatre Pkwy")
      8. addressComponent2.put("short_name", "Amphitheatre Pkwy")
      9. addressComponents.add(addressComponent2)
      10. // ...List<Map<String, List<Map<String, String>>>> results = new ArrayList<Map<String, List<Map<String, String>>>>()
      11. Map<String, List<Map<String, String>>> result1 = new HashMap<String, List<Map<String,String>>>()
      12. result1.put("address_components", addressComponents)
      13. results.add(result1)
      14. // ...Map<String, List<Map<String, List<Map<String, String>>>>> god = new HashMap<String, List<Map<String,List<Map<String,String>>>>>()
      15. god.put("results", results)
      16. String json = new Gson().toJson(god)
      17. System.out.println(json)
      18. // There!

      Positive Reactions
      1. Excellent, thank you!
      2. Thank you for your knowledge and advice.
      3. Thank you.
      4. Map and List ARE dynamically resizable.
      5. Question for all: Is it possible to dynamically resize HashTable/HashMap, Map structures?
      6. Hashtable is the legacy predecesor of HashMap which was succeeded over a decade ago (read up to date tutorials/books please).
      7. I appreciate your help.
      8. Does Java have built-in functionality to dynamically resize hashes?
      Other Reactions
      1. Just call add() or put() to add new items, exactly as in my answer.
      2. Or, must you write out each addressComponent (i.e.
      3. HashMap is an implementation.
      4. I will take a look at the link and study it.
      5. URL_http://download.oracle.com/javase/tutorial/collections/interfaces/map.html .
      6. Click the tutorial link in my previous comment to learn more about it.
      7. addresscomponent1, addressComponent2,..., addressComponentN)?
      8. Does this work for N number of results from, say, a SQL lookup?
      9. Map is an interface.
      10. Just do it in a loop.
      11. What is the difference between Map and HashMap/HashTable?
      12. I've been investigating and, so far, I haven't found an answer, other than Linked Lists.

    10. How to get data through JSON in a particular format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. ArrayList<MyUser> mul = new ArrayList<MyUser>()
      2. if (status == true) { ... ... for(RosterEntry r:entries) { if(...){ ... } else { mul.add(new MyUser(r.getName(),r.getUser())
      3. count2++
      4. } }response.setContentType("application/json")
      5. response.getWriter().write(new Gson().toJSON(mul))
      6. response.setCharacterEncoding("utf-8")
      7. response.sendRedirect("Roster.jsp")

  13. Including a top level element with Gson

    You're welcome. I have no idea what Gson is but I imagine something like this would work . .. details

    1. return gson.toJson({pojos:pojos})

    Positive Reactions
    1. Thanks but I'm using Java, I think that would not work.

    • See Also (4)
    1. Deserializing Generic Types with GSON

      Have you tried. EDIT After reading deserialize-listclass-object-generic-type this post it seems that you use of Type is correct. details

      Reactions - Positive 2, Negative 0, Others 0

      1. gson.create().fromJson(reader, MyJson.class)

      Positive Reactions
      1. I didn't know about Type Erasure so thanks for pointing me on it.
      2. OK my solution is to send Type as parameter when creating JsonDownloader class, then everything works fine.

    2. Read embedded object in Jackson

      Then use this object to fill out your Item and Author objects and create the correct relationships. Your Item class could only be automatically deserialized from the following form You might be able to do something with custom deserialization but it would not be the simpler solution for sure. details

      Reactions - Positive 3, Negative 0, Others 0

      1. //... the deserialized original JSON ItemLegacy legacy ... // create an author Author author = new Author()
      2. author.setName(legacy.getName())
      3. author.setGroup(legacy.getGroup())
      4. ... // create an item Item item = new Item()
      5. item.setTitle(legacy.getTitle())
      6. ... // finally set the author... and you should have the desired structure item.setAuthor(author)

      Positive Reactions
      1. All I need is to deserialize from legacy JSON into well-formed objects.
      2. I hope my edits clarify that I was not talking about serialization...
      3. I was hoping that Jackson provides an equivalent of the Hibernate's @Embeddable/@Embedded.
      Other Reactions
      1. @Crozin: I see what you mean.
      2. Oh, now I get it.
      3. I don't need to serialize to the proper JSON.
      4. If there is such a feature, I am unaware of it.

    3. Using GSON to parse array with multiple types

      Of course deserializing a single-component array into a non-array type is not required. For example the previous example could be deserialized as . details

      Reactions - Positive 0, Negative 0, Others 0

      1. int[] data = gson.fromJson("[3]", int[].class)

    4. Using GSON to parse array with multiple types

      Gson has special handling for deserializing some single-component arrays into a non-array type. For example would assign the int value 3 to data. details

      Reactions - Positive 0, Negative 0, Others 0

      1. int data = gson.fromJson("[3]", int.class)

  14. Adding an existing json string with Gson

    Simple convert your bean to a JsonObject and add a property. prints . .. details

    1. Gson gson = new Gson()
    2. JsonObject object = (JsonObject) gson.toJsonTree(new Wrapper())
    3. object.addProperty("content", "arbitrary_json_string")
    4. System.out.println(object)

    Other Reactions
    1. @LutzHorn You can use JsonObject#add(JsonElement) for that.
    2. Does this work if the "arbitrary_json_string" is a JSON object*?

  15. java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 62

    None .. details

    1. ProductInfo productInfo = gson.fromJson(reader, ProductInfo.class)

    • See Also (2)
    1. gson error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 166

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. gson.toJson(solrDoc)

    2. deserialize JSON data for different types of objects

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. gson.fromJson(jsonObject, AppropriateBean.class)

  16. Converting JSON to Hashmap&lt;String, POJO&gt; using GWT

    If you want client/server side serialize/deserialize JSON in GWT code. In GWT 2.1.1 you can use toolkit/wiki/AutoBean GWT-AutoBean-framework I've not tried with complex and low level with Map you can go with doc Finally if you want to gson on client side with GWT then you have to try bGwtGson library . .. details

    1. String serializeToJson(Test test) { // Retrieve the AutoBean controller AutoBean<Test> bean = AutoBeanUtils.getAutoBean(test)
    2. return AutoBeanCodex.encode(bean).getPayload()
    3. }Test deserializeFromJson(String json) { AutoBean<Test> bean = AutoBeanCodex.decode(myFactory, Test.class, json)
    4. return bean.as()
    5. }

    Positive Reactions
    1. if you want to gson on client side then you have to try this library URL_https://github.com/heroandtn3/bGwtGson .
    2. AutoBeans works, but they are some kind of buggy especially if you use Maps or Lists.
    Negative Reactions
    1. @Christian Kuetbach you can deserializing/serialize with GWT AutoBean framework at client/server side, but i have not tried with complex Java Map.
    Other Reactions
    1. I think in GWT client code one can't use GSON.
    2. yeah its for Server-side Deserializing/serializing JSON with GWT not for the client.
    3. And you should not work with concrete types.
    4. You should use the Map- Interface.
    5. In fact, I think AutoBeans are really buggy.
    6. Sometimes you will need to recreate the beans, f you modify the content of a map.

  17. Create JsonArray without key value

    You can do something like which outputs . What your are trying to do is just to fill an array with primitive variables to achieve that you have to change your code like this . .. details

    1. private String generate(String value) { Gson gson = new Gson()
    2. JsonArray jsonArray = new JsonArray()
    3. jsonArray.add(new JsonPrimitive(value))
    4. return gson.toJson(jsonArray)
    5. }

  18. Create JsonArray without key value

    . You can do something like which outputs . .. details

    1. Gson gson = new Gson()
    2. JsonArray array = new JsonArray()
    3. array.add(new JsonPrimitive("one"))
    4. array.add(new JsonPrimitive("two"))
    5. array.add(new JsonPrimitive("three"))
    6. JsonObject jsonObject = new JsonObject()
    7. jsonObject.add("main", array)
    8. System.out.println(gson.toJson(jsonObject))

    • See Also (1)
    1. GSON how to parse array with dynamic type

      The first thing is parsing this json file to java that can be done this way Then make a class which will have all the values you got from the json file.Say that class is MyClass containing all of the values you got from json file. make MyClass object and then I hope this is what you want. details

      Reactions - Positive 0, Negative 0, Others 0

      1. MyClass obj = new MyClass()
      2. Gson gson = new Gson()
      3. JSONObject onj = new JSONObject()
      4. JSONArray userDataValues = new JSONArray()
      5. //again convert to jsonuserDataValues.put(new JSONObject(gson.toJson(obj)))
      6. //serialized the objectonj.put("property", userDataValues)

  19. Android - Parse JSON using GSON

    None .. details

    1. package stackoverflow.questions
    2. import com.google.gson.*
    3. import com.google.gson.reflect.TypeToken
    4. import java.lang.reflect.Type
    5. import java.util.*
    6. public class Q20337652 {
    7. public static class Term {
    8. String term
    9. String POS
    10. String sense
    11. String usage
    12. @Override
    13. public String toString() {
    14. return "Term [term=" + term + ", POS=" + POS + ", sense=" + sense + ", usage=" + usage + "]"
    15. }
    16. }
    17. public static class Item {
    18. Term OriginalTerm
    19. Term FirstTranslation
    20. String Note
    21. @Override
    22. public String toString() {
    23. return "Item [OriginalTerm="
    24. + OriginalTerm
    25. + ", FirstTranslation="
    26. + FirstTranslation
    27. + ", Note="
    28. + Note
    29. + "]"
    30. }
    31. }
    32. public static void main(String[] args) {
    33. String json =
    34. " { "
    35. + " "
    36. + " \"term0\" : { "
    37. + " \"PrincipalTranslations\" : { "
    38. + " \"0\" :{ "
    39. + " \"OriginalTerm\" : { \"term\" : \"cat\", \"POS\" : \"n\", \"sense\" : \"domestic animal\", \"usage\" : \"\"}, "
    40. + " \"FirstTranslation\" : {\"term\" : \"gato\", \"POS\" : \"nm\", \"sense\" : \" \"}, \"Note\" : \"\"}, "
    41. + " \"1\" :{ "
    42. + " \"OriginalTerm\" : { \"term\" : \"cat\", \"POS\" : \"n\", \"sense\" : \"member of cat family\", \"usage\" : \"\"}, "
    43. + " \"FirstTranslation\" : {\"term\" : \"felino\", \"POS\" : \"nm\", \"sense\" : \"familia de animales\"}, \"Note\" : \"\"}},"
    44. + " \"AdditionalTranslations\" : { "
    45. + " \"0\" :{ "
    46. + " \"OriginalTerm\" : { \"term\" : \"cat\", \"POS\" : \"n\", \"sense\" : \"guy\", \"usage\" : \"slang\"}, "
    47. + " \"FirstTranslation\" : {\"term\" : \"to, tipo, chaval\", \"POS\" : \"nm\", \"sense\" : \"coloq\"}, "
    48. + " \"SecondTranslation\" : {\"term\" : \"vato\", \"POS\" : \"\", \"sense\" : \"Mex\"}, \"Note\" : \"\"}, "
    49. + " "
    50. + " \"original\" : { "
    51. + " \"Compounds\" : { "
    52. + " \"0\" :{ "
    53. + " \"OriginalTerm\" : { \"term\" : \"alley cat\", \"POS\" : \"n\", \"sense\" : \"stray cat\", \"usage\" : \"\"}, "
    54. + " \"FirstTranslation\" : {\"term\" : \"gato callejero\", \"POS\" : \"nm\", \"sense\" : \"\"}, \"Note\" : \"\"}, "
    55. + " \"Lines\" : \"End Reached\", \"END\" : true "
    56. + " "
    57. + " } "
    58. + " } }}} "
    59. JsonParser jp = new JsonParser()
    60. JsonElement je = jp.parse(json)
    61. JsonElement je2 = je.getAsJsonObject().get("term0")
    62. JsonElement je3 = je2.getAsJsonObject().get("PrincipalTranslations")
    63. Type mapType = new TypeToken<Map<String, Item>>() {}.getType()
    64. Map<String, Item> principalTranslation = new Gson().fromJson(je3, mapType)
    65. System.out.println(principalTranslation)
    66. }
    67. }

    • See Also (2)
    1. Parse JSON number array using Gson

      If you need mode details on how it works feel free to ask. This is my execution If your data changes of course you have to change this code according. details

      Reactions - Positive 2, Negative 0, Others 0

      1. package stackoverflow.questions
      2. import com.google.gson.*
      3. import com.google.gson.reflect.TypeToken
      4. import java.lang.reflect.Type
      5. import java.util.List
      6. public class Q20118749 {
      7. /** * @param args */
      8. public static void main(String[] args) {
      9. String json =
      10. "{\"values\":[[1,1,0,0,0,0,11,0.09090909090909091],[[0,0,0,0,0,1,0],[0,0,0,0,0,1,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,11,0],[0,0,0,0,0,0.09090909090909091,0]]]}"
      11. JsonElement je = new JsonParser().parse(json)
      12. JsonArray list = je.getAsJsonObject().get("values").getAsJsonArray()
      13. // to get rid of the value part Type listType1 = new TypeToken<List<Double>>() {}.getType()
      14. Type listType2 = new TypeToken<List<List<Double>>>() {}.getType()
      15. Gson g = new Gson()
      16. List<Double> listOfDouble = g.fromJson(list.get(0), listType1)
      17. List<List<Double>> listOfListOfDouble = g.fromJson(list.get(1), listType2)
      18. System.out.println(listOfDouble)
      19. System.out.println(listOfListOfDouble)
      20. }
      21. }

      Positive Reactions
      1. thanks,it fixed,but it is not convient for me.
      2. I update my question,Thanks for answer me.But I really want to write a class using the class.Thanks.
      Other Reactions
      1. Is your JSON fixed?
      2. What exactly does not satisfy you?

    2. How to prevent Gson from converting a long number (a json string ) to scientific notation format?

      This will return the Gson object representations JsonElement rather than a user defined class but avoids the problem of conversion to scientific notation. Code Output . details

      Reactions - Positive 0, Negative 3, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.JsonElement
      3. import com.google.gson.JsonParser
      4. import com.google.gson.reflect.TypeToken
      5. import java.lang.reflect.Type
      6. import java.util.Map
      7. public class GsonTest {
      8. public static void main(String[] args) {
      9. String json = "{numbers:[268627104,485677888,506884800]}"
      10. Gson gson = new Gson()
      11. Type type = new TypeToken<Map<String, Object>>() {}.getType()
      12. Map<String, Object> jsonMap = gson.fromJson(json, type)
      13. System.out.println("Gson output:")
      14. System.out.println(jsonMap)
      15. JsonParser jsonParser = new JsonParser()
      16. JsonElement jsonElement = jsonParser.parse(json)
      17. System.out.println("JsonParser output:")
      18. System.out.println(jsonElement)
      19. }
      20. }

      Negative Reactions
      1. It's just OUTPUT to String give you correct format, but if u try serialize class of this jsonElement i got not corrects Long values.
      2. I resorted to the format approach as my json string was very complicated and I had to extract each number before I could use it for display purpose.
      3. The [Gson Javadoc for JsonElement]( URL_http://google-gson.googlecode.com/svn/trunk /gson/docs/javadocs/index.html?com/google/gson/JsonElement.html) does not mention that class implementing serializable so I could see that being a problem.
      Other Reactions
      1. The JsonParser approach shall work.
      2. You could always transfer the data from the Gson object to your own object though.

  20. Deserialize recursive polymorphic class in GSON

    Of course it can be improve to manage borderline cases for example what happens if you do not have type field?). This is the result of my code . .. details

    1. package stackoverflow.questions
    2. import java.lang.reflect.Type
    3. import java.util.*
    4. import stackoverflow.questions.Q20254329.*
    5. import com.google.gson.*
    6. import com.google.gson.reflect.TypeToken
    7. public class Q20327670 { static class Complex implements Recursive { Map<String, Recursive> map
    8. @Override public String toString() { return "Complex [map=" + map + "]"
    9. } } static class Simple implements Recursive { @Override public String toString() { return "Simple []"
    10. } } public static class RecursiveDeserializer implements JsonDeserializer<Recursive> { public Recursive deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Recursive r = null
    11. if (json == null) r = null
    12. else { JsonElement t = json.getAsJsonObject().get("type")
    13. String type = null
    14. if (t != null) { type = t.getAsString()
    15. switch (type) { case "complex": { Complex c = new Complex()
    16. JsonElement e = json.getAsJsonObject().get("map")
    17. if (e != null) { Type mapType = new TypeToken<Map<String, Recursive>>() {}.getType()
    18. c.map = context.deserialize(e, mapType)
    19. } r = c
    20. break
    21. } case "simple": { r = new Simple()
    22. break
    23. } // remember to manage default.. } } } return r
    24. } } public static void main(String[] args) { String json = " { " + " \"type\" : \"complex\", " + " \"map\" : { " + " \"a\" : { " + " \"type\" : \"simple\" " + " }, " + " \"b\" : { " + " \"type\" : \"complex\", " + " \"map\" : { " + " \"ba\" : { " + " \"type\" : \"simple\" " + " } " + " } " + " } " + " } } "
    25. GsonBuilder gb = new GsonBuilder()
    26. gb.registerTypeAdapter(Recursive.class, new RecursiveDeserializer())
    27. Gson gson = gb.create()
    28. Recursive r = gson.fromJson(json, Recursive.class)
    29. System.out.println(r)
    30. }}

    Positive Reactions
    1. Ok great!
    2. More or less.. but I'd like it to stay as clear as possible.
    3. Hey thanks, this could work.
    4. If you have a spare minute I'd appreciate a working example of how to do it properly (both for me and future visitors); in the meantime, grab an accept, you've earned it!.
    5. Should be simple to adapt the answer deserializer to this kind of JSON.
    Negative Reactions
    1. If you can put "type" outside the Class serialization, it does the trick.
    2. But imagine that I have many more properties inside both Complex and Simple class.. then I'd have to manually deserialize each field (..get("map");) essentially losing all the auto-magic GSON gives me.
    Other Reactions
    1. Any ideas?
    2. I can show you, but not now.
    3. I think I can prepare a full example within next 24 hours.
    4. And what if there are not 2, but 10 subclasses?
    5. Any case, only with running code I can state this for sure.
    6. Can you control the JSON or not?
    7. { type: "complex", instance: { map: { ... } } } meaning that type is not on the same level as actual class fields (here nested inside the instance element) ?
    8. this would be ok?
    9. Yes, you got it.

  21. Deserialize a JSON that changes internal nodes

    Here's the code you can copy&paste&run. This is my result . .. details

    1. package stackoverflow.questions
    2. import com.google.gson.*
    3. import com.google.gson.reflect.TypeToken
    4. import java.lang.reflect.Type
    5. import java.util.*
    6. public class Q20254329 {
    7. public static class Address {
    8. private String street
    9. private String postalCode
    10. @Override
    11. public String toString() {
    12. return "Address [street=" + street + ", postalCode=" + postalCode + "]"
    13. }
    14. }
    15. public static class Card {
    16. private String firstName
    17. private String lastName
    18. private Address address
    19. private List<String> phoneNumbers
    20. @Override
    21. public String toString() {
    22. return "Card [firstName="
    23. + firstName
    24. + ", lastName="
    25. + lastName
    26. + ", address="
    27. + address
    28. + ", phoneNumbers="
    29. + phoneNumbers
    30. + "]"
    31. }
    32. }
    33. public static class CardDeserializer implements JsonDeserializer<Card> {
    34. public Card deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    35. throws JsonParseException {
    36. if (json == null) return null
    37. else {
    38. Card c = new Card()
    39. JsonObject jo = json.getAsJsonObject()
    40. c.firstName = jo.get("firstName").getAsString()
    41. c.lastName = jo.get("lastName").getAsString()
    42. JsonElement ja = jo.get("address")
    43. if (jo.get("address").isJsonObject()) {
    44. c.address = context.deserialize(ja, Address.class)
    45. } else {
    46. c.address = new Address()
    47. c.address.street = jo.get("address").getAsString()
    48. c.address.postalCode = jo.get("postalCode").getAsString()
    49. }
    50. JsonElement jsonPhoneNumbers = jo.get("phoneNumbers")
    51. if (jsonPhoneNumbers != null) {
    52. Type listType = new TypeToken<List<String>>() {}.getType()
    53. c.phoneNumbers = context.deserialize(jsonPhoneNumbers, listType)
    54. }
    55. JsonElement jsonPhoneNumber = jo.get("phoneNumber")
    56. if (jsonPhoneNumber != null) {
    57. c.phoneNumbers = new ArrayList<>()
    58. //java7 here c.phoneNumbers.add(jsonPhoneNumber.getAsString())
    59. }
    60. return c
    61. }
    62. }
    63. }
    64. public static void main(String[] args) {
    65. String s1 =
    66. " { "
    67. + " \"firstName\": \"X\", "
    68. + " \"lastName\": \"XXX\", "
    69. + " \"address\": { "
    70. + " \"street\": \"John Street, 10\", "
    71. + " \"postalCode\": \"12311\" "
    72. + " }, "
    73. + " \"phoneNumbers\": [ "
    74. + " \"812 123-1234\", "
    75. + " \"916 123-4567\" "
    76. + " ] "
    77. + "} "
    78. String s2 =
    79. "{ "
    80. + " \"firstName\": \"X\", "
    81. + " \"lastName\": \"XXX\", "
    82. + " \"address\": \"John Street, 10\", "
    83. + " \"postalCode\": \"101101\", "
    84. + " \"phoneNumber\": \"812123-1234\" "
    85. + "} "
    86. GsonBuilder builder = new GsonBuilder()
    87. builder.registerTypeAdapter(Card.class, new CardDeserializer())
    88. Gson gson = builder.create()
    89. Card c1 = gson.fromJson(s1, Card.class)
    90. System.out.println("First json " + c1)
    91. Card c2 = gson.fromJson(s2, Card.class)
    92. System.out.print("Second json " + c2)
    93. }
    94. }

    • See Also (1)
    1. how to use gson handle dynamic response data? (json to java object)

      Putting lowercase won't change Gson behavior since it looks at class fields name not to class names. this is the execution of code . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package stackoverflow.questions.q19124387
      2. import java.lang.reflect.Type
      3. import java.util.*
      4. import com.google.gson.*
      5. import com.google.gson.reflect.TypeToken
      6. public class Q19124387 { public static class User { private String name
      7. private String age
      8. private String gender
      9. @Override public String toString() { return "User [name=" + name + ", age=" + age + ", gender=" + gender + "]"
      10. } } public static class Result { private List<User> users = new ArrayList<User>()
      11. } public static class Response { private Result result
      12. } public static class Data { private Response response
      13. } public static class CustomDeserializer implements JsonDeserializer<Result> { public Result deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Result r = null
      14. JsonElement usersField = json.getAsJsonObject().get("users")
      15. if (usersField.isJsonNull() || usersField.isJsonPrimitive())
      16. // if is null or is a primitive type will return an empty result else if (usersField.isJsonObject()) { r = new Result()
      17. r.users.add((User) context.deserialize(usersField, User.class))
      18. } else if (usersField.isJsonArray()) { Type listOfUserType = new TypeToken<List<User>>() {}.getType()
      19. r = new Result()
      20. r.users.addAll((Collection<? extends User>) context.deserialize(usersField, listOfUserType))
      21. } return r
      22. } } /** * @param args */ public static void main(String[] args) { String json1 = " {\"response\": { \"result\": { \"users\": [{ name: \"ABC\", age: \"20\", gender: \"F\" }, { name: \"cbd\", age: \"23\", gender: \"M\" }] } } }"
      23. String json2 = "{\"response\": { \"result\": {\"users\": { name: \"ABC\", age: \"20\",gender: \"F\" } } } } "
      24. Gson g = new Gson()
      25. try { Data d1 = g.fromJson(json1, Data.class)
      26. System.out.println("Parsed json1, list of users")
      27. } catch (Exception e) { System.out.println("Cannot parse json1, list of users")
      28. } try { Data d2 = g.fromJson(json2, Data.class)
      29. System.out.println("Parsed json2, single user")
      30. } catch (Exception e) { System.out.println("Cannot parse json2, single user")
      31. } GsonBuilder gb = new GsonBuilder()
      32. gb.registerTypeAdapter(Result.class, new CustomDeserializer())
      33. Gson g2 = gb.create()
      34. Data d1 = g2.fromJson(json1, Data.class)
      35. Data d2 = g2.fromJson(json2, Data.class)
      36. System.out.println("Second user of json1 is " + d1.response.result.users.get(1))
      37. System.out.println("First user of json2 is " + d2.response.result.users.get(0))
      38. }}

  22. how do I deserialize array of different objects with GSON

    None .. details

    1. private static List<? extends Item> getDatalsomJson(String jsonString) { Type type = new TypeToken<List<? extends JsonResponse.Item>>(){}.getType()
    2. GsonBuilder gb = new GsonBuilder()
    3. gb.registerTypeAdapter(type, new JsonResponse.JsonResponseDeserialize())
    4. Gson gson = gb.create()
    5. List<? extends Item> ls = gson.lsomJson(jsonString, type)
    6. return ls
    7. }

    • See Also (1)
    1. Android : parsing large json response

      2. Register the type adapter to you GsonBuilder like The deserialize method could look like . details

      Reactions - Positive 0, Negative 0, Others 0

      1. new GsonBuilder().registerTypeAdapter(new TypeToken<List<Team>>() {}.getType(), new CoupleAdapter()).create()

      Other Reactions
      1. what is your goal?
      2. Can I register two or more TypeAdapter for large response.
      3. See...question is edited.
      4. I tried and goes to infinitr loop.
      5. because deserialize called infinitely.
      6. I tested.

  23. how do I deserialize array of different objects with GSON

    do like this Your data Your pojos here the deserialized array. . .. details

    1. JsonParser parser = new JsonParser()
    2. JsonArray Jarray = parser.parse(json).getAsJsonArray()
    3. Gson gson = new Gson()
    4. for(JsonElement obj : Jarray ) { JsonResponse jsonResponse = gson.fromJson( obj , JsonResponse.class)
    5. System.out.println(jsonResponse)
    6. }

    • See Also (2)
    1. Can't Convert string to JsonArray

      Below is just a minor modification of your code in the main method. Lastly remember to prefix your statement com.google.gson. details

      Reactions - Positive 1, Negative 1, Others 0

      1. System.out.println("String to Json Array Stmt")
      2. JsonParser parser = new JsonParser()
      3. JsonElement tradeElement = parser.parse(s)
      4. JsonArray trade = tradeElement.getAsJsonArray()
      5. System.out.println(trade)

      Positive Reactions
      1. You mean getting the first element ([\"110917 \", 3.0099999999999998, -0.72999999999999998, 2.8500000000000001, 2.96, 685.0, 38603.0]) of JsonArray "trade"?
      Negative Reactions
      1. Here typo mistaken for import in the question .actually added in source..thanks.
      Other Reactions
      1. Is it Possible to split the JsonArray?
      2. Try using "trade.get(0)".

    2. Can't Convert string to JsonArray

      I don't see the problem. This code runs fine for me The only problem maybe is that you failed to properly escape the double quotes in your s string literal. details

      Reactions - Positive 1, Negative 2, Others 0

      1. import com.google.gson.JsonArray
      2. import com.google.gson.JsonElement
      3. import com.google.gson.JsonParser
      4. public class GsonExample {
      5. public static void main(String[] args) {
      6. String s =
      7. "[[\"110917\", 3.0099999999999998, -0.72999999999999998,"
      8. + "2.8500000000000001, 2.96, 685.0, 38603.0], [\"110917\", 2.71,"
      9. + "0.20999999999999999, 2.8199999999999998, 2.8999999999999999,"
      10. + "2987.0, 33762.0]]"
      11. JsonParser parser = new JsonParser()
      12. JsonElement elem = parser.parse(s)
      13. JsonArray elemArr = elem.getAsJsonArray()
      14. System.out.println(elemArr)
      15. }
      16. }

      Positive Reactions
      1. Thanks @Mike ;-).
      Negative Reactions
      1. The slash is to escape the " character.
      2. May i know why here we need to add /(backward slash) in front of strings?
      Other Reactions
      1. elemArr.get( index ) can be used to return the first element of the array for example.
      2. If you don't do it the compiler can't know you're not intending to end the string for example with a closing ".
      3. Is it possible to pass?
      4. See here: URL_http://en.wikipedia.org/wiki/Escape_character .
      5. Just I want first list only as a json array?

  24. How to create more than one object with Gson and how can different objects explicit referenced in a Java class by using one JSON file?

    I prepared a code that you can copy&run in your IDE to show how to do it. and this is my execution The key part is extractFromJson method that does all the job. .. details

    1. package stackoverflow.questions.q19997365
    2. import com.google.gson.*
    3. public class Q19997365 {
    4. public static class Person {
    5. String id
    6. String name
    7. @Override
    8. public String toString() {
    9. return "Person [id=" + id + ", name=" + name + "]"
    10. }
    11. }
    12. public static class Account {
    13. String accountid
    14. String accountnumber
    15. @Override
    16. public String toString() {
    17. return "Account [accountid=" + accountid + ", accountNumber=" + accountnumber + "]"
    18. }
    19. }
    20. public static class Transaction {
    21. String id
    22. String date
    23. @Override
    24. public String toString() {
    25. return "Transaction [id=" + id + ", date=" + date + "]"
    26. }
    27. }
    28. /** * @param args */
    29. public static void main(String[] args) {
    30. String json1 = "{\"id\" : \"1\", \"name\" : \"David\"}"
    31. // this represent testdata for the class Person String json2 = "{\"accountid\" : \"1188\", \"accountnumber\" : \"119295567\"}"
    32. // this represent testdata for the class account String json3 = "{\"id\" : \"22\", \"date\" : \"22.11.2013\"}"
    33. // this represent testdata for the class transaction System.out.println(extractFromJson(json1))
    34. System.out.println(extractFromJson(json2))
    35. System.out.println(extractFromJson(json3))
    36. }
    37. private static Object extractFromJson(String json) {
    38. Gson g = new Gson()
    39. JsonObject e = new JsonParser().parse(json).getAsJsonObject()
    40. if (e.get("name") != null) return g.fromJson(json, Person.class)
    41. if (e.get("accountid") != null) return g.fromJson(json, Account.class)
    42. if (e.get("date") != null) return g.fromJson(json, Transaction.class)
    43. return null
    44. }
    45. }

  25. Spring MVC @RequestBody receive an Object wrapper with non-primitive attributes

    As you know I create the following json from the view I changed it a little bit because I realised that is not necessary to create a object Subscription and a var Subscription. If you build the JSON like this it will work perfectly The controller receives this json And the SubscriptionWrapper So What is the problem. .. details

    1. var manager = { username: "admin", password: "admin"}
    2. var userToSubscribe = { username: "newuser", password: "newpassword", email: "user@1and1.es"}
    3. var openid = "https://myopenid..."
    4. $.ajax({ url: '/dp/rest/isUserSuscribed.json', type: 'POST', dataType: 'json', contentType: 'application/json', mimeType: 'application/json', data: JSON.stringify({manager : manager, userToSubscribe : userToSubscribe, openid : openid}) })

    • See Also (1)
    1. Parsing GSON Google Places API

      You are using your Gson instance wrong. It should be you do NOT need to call Gson can directly serialize from an object. details

      Reactions - Positive 1, Negative 0, Others 0

      1. gson.toJson(ritorno)

      Positive Reactions
      1. Hey man, thank you very much... the way that I was calling was wrong...Instead of that, now I'm calling like this: CODESNIPPET_JAVA11 .
      Other Reactions
      1. Why do you keep on calling the ritorno.toString() method?

  26. Gson: Unable to parse date

    None .. details

    1. package stackoverflow.questions.q14197557
    2. import com.google.gson.*
    3. import java.lang.reflect.Type
    4. import java.util.Date
    5. public class Q14197557 {
    6. public static class MyType {
    7. String user
    8. Date date
    9. @Override
    10. public String toString() {
    11. return "MySample [user=" + user + ", date=" + date + "]"
    12. }
    13. }
    14. public static class MySampleDeserializer implements JsonDeserializer<MyType> {
    15. public MyType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    16. throws JsonParseException {
    17. if (json == null) return null
    18. else {
    19. MyType s = new MyType()
    20. s.user = json.getAsJsonObject().get("user").getAsString()
    21. s.date = new Date(json.getAsJsonObject().get("date").getAsLong())
    22. return s
    23. }
    24. }
    25. }
    26. public static void main(String[] args) {
    27. String json = "{ user: \"sample-user\", date : 1225864800 }"
    28. GsonBuilder gsonBuilder = new GsonBuilder()
    29. gsonBuilder.registerTypeAdapter(MyType.class, new MySampleDeserializer())
    30. MyType s = gsonBuilder.create().fromJson(json, MyType.class)
    31. System.out.println("My Type: " + s)
    32. }
    33. }

    • See Also (3)
    1. (Gson) JSON to Java objects containing ArrayList<Class>

      As I can see my code should work correctly right. do like this . details

      Reactions - Positive 2, Negative 1, Others 0

      1. final String json = "{\"id\":81,\"nomes\":[{\"id\":124,\"nome\":\"aleluia\",\"etimologia\":\"asasiajisjaijs\"},{\"id\":126,\"nome\":\"amm\",\"etimologia\":\"asasiajisjaijs\"}],\"significados\":[{\"id\":67,\"significado\":\"asasjaijsiajsoijaoisjaoisj\",\"categoria\":{\"id\":3,\"nome\":\"Nada\",\"descricao\":\"asuahushaus\",\"serie\":1}}],\"totalAcessos\":0,\"dataLancamento\":1382066568000,\"relevancia\":0}"
      2. GsonBuilder gsonBuilder = new GsonBuilder()
      3. gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { Calendar calendar = Calendar.getInstance()
      4. calendar.setTimeInMillis(jsonElement.getAsLong())
      5. return calendar.getTime()
      6. } })
      7. Gson gson = gsonBuilder.create()
      8. Verbete verbete = gson.fromJson(json, Verbete.class)
      9. System.out.println(verbete)

      Positive Reactions
      1. Interesting!
      2. It worked!
      Negative Reactions
      1. So, the problem was in to convert from milliseconds to Date object?

    2. let Gson throw exceptions on wrong types

      You could also improve on the exception handling by creating your own exception and pass it to the JsonParseException so it can be detected via in the caller. That all said in the vast majority of cases this will work Output . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class App {
      2. public static void main(String[] args) {
      3. Gson gson =
      4. new GsonBuilder()
      5. .registerTypeAdapter(
      6. TestAnnotationBean.class, new AnnotatedDeserializer<TestAnnotationBean>())
      7. .create()
      8. String json = "{\"foo\":\"This is foo\",\"bar\":\"this is bar\"}"
      9. TestAnnotationBean tab = gson.fromJson(json, TestAnnotationBean.class)
      10. System.out.println(tab.foo)
      11. System.out.println(tab.bar)
      12. json = "{\"foo\":\"This is foo\"}"
      13. tab = gson.fromJson(json, TestAnnotationBean.class)
      14. System.out.println(tab.foo)
      15. System.out.println(tab.bar)
      16. json = "{\"bar\":\"This is bar\"}"
      17. tab = gson.fromJson(json, TestAnnotationBean.class)
      18. System.out.println(tab.foo)
      19. System.out.println(tab.bar)
      20. }
      21. }
      22. @Retention(RetentionPolicy.RUNTIME)
      23. @Target(ElementType.FIELD)
      24. @interface JsonRequired {}
      25. class TestAnnotationBean {
      26. @JsonRequired public String foo
      27. public String bar
      28. }
      29. class AnnotatedDeserializer<T> implements JsonDeserializer<T> {
      30. public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
      31. throws JsonParseException {
      32. T pojo = new Gson().fromJson(je, type)
      33. Field[] fields = pojo.getClass().getDeclaredFields()
      34. for (Field f : fields) {
      35. if (f.getAnnotation(JsonRequired.class) != null) {
      36. try {
      37. f.setAccessible(true)
      38. if (f.get(pojo) == null) {
      39. throw new JsonParseException("Missing field in JSON: " + f.getName())
      40. }
      41. } catch (IllegalArgumentException ex) {
      42. Logger.getLogger(AnnotatedDeserializer.class.getName()).log(Level.SEVERE, null, ex)
      43. } catch (IllegalAccessException ex) {
      44. Logger.getLogger(AnnotatedDeserializer.class.getName()).log(Level.SEVERE, null, ex)
      45. }
      46. }
      47. }
      48. return pojo
      49. }
      50. }

    3. Using GSON to parse array with multiple types

      Similar to the following example. The Gson user guide does cover handling deserialization of collections of mixed types with a similar example as this in Deserializing-Collection-with-Objects-of-Arbitrary-Types the-"Serializing and-Deserializing-Collection-with-Objects-of-Arbitrary-Types"-section . details

      Reactions - Positive 0, Negative 0, Others 0

      1. // output: // [{MyThreeThings: first=hello, second=1, third=[2]}, // {MyThreeThings: first=world, second=3, third=[4, 5]}]import java.lang.reflect.Type
      2. import com.google.gson.Gson
      3. import com.google.gson.GsonBuilder
      4. import com.google.gson.JsonArray
      5. import com.google.gson.JsonDeserializationContext
      6. import com.google.gson.JsonDeserializer
      7. import com.google.gson.JsonElement
      8. import com.google.gson.JsonParseException
      9. import java.util.Arrays
      10. public class FooToo {
      11. static String jsonInput = "[" + "[\"hello\",1,[2]]," + "[\"world\",3,[4,5]]" + "]"
      12. public static void main(String[] args) {
      13. GsonBuilder gsonBuilder = new GsonBuilder()
      14. gsonBuilder.registerTypeAdapter(MyThreeThings.class, new MyThreeThingsDeserializer())
      15. Gson gson = gsonBuilder.create()
      16. MyThreeThings[] things = gson.fromJson(jsonInput, MyThreeThings[].class)
      17. System.out.println(Arrays.toString(things))
      18. }
      19. }
      20. class MyThreeThings {
      21. String first
      22. int second
      23. int[] third
      24. MyThreeThings(String first, int second, int[] third) {
      25. this.first = first
      26. this.second = second
      27. this.third = third
      28. }
      29. @Override
      30. public String toString() {
      31. return String.format(
      32. "{MyThreeThings: first=%s, second=%d, third=%s}", first, second, Arrays.toString(third))
      33. }
      34. }
      35. class MyThreeThingsDeserializer implements JsonDeserializer<MyThreeThings> {
      36. @Override
      37. public MyThreeThings deserialize(
      38. JsonElement json, Type typeOfT, JsonDeserializationContext context)
      39. throws JsonParseException {
      40. JsonArray jsonArray = json.getAsJsonArray()
      41. String first = jsonArray.get(0).getAsString()
      42. int second = jsonArray.get(1).getAsInt()
      43. JsonArray jsonArray2 = jsonArray.get(2).getAsJsonArray()
      44. int length = jsonArray2.size()
      45. int[] third = new int[length]
      46. for (int i = 0 i < length i++) {
      47. int n = jsonArray2.get(i).getAsInt()
      48. third[i] = n
      49. }
      50. return new MyThreeThings(first, second, third)
      51. }
      52. }

  27. Gson deserialize internal part

    None .. details

    1. public class Q13363304 {
    2. class Org {
    3. String State
    4. String Guid
    5. int Id
    6. String Name
    7. String ShortName
    8. @Override
    9. public String toString() {
    10. return "Org [State="
    11. + State
    12. + ", Guid="
    13. + Guid
    14. + ", Id="
    15. + Id
    16. + ", Name="
    17. + Name
    18. + ", ShortName="
    19. + ShortName
    20. + "]"
    21. }
    22. }
    23. /** * @param args */
    24. public static void main(String[] args) {
    25. String json =
    26. "{ \"LightObjectSet\": { \"Objects\": { \"Org\": { \"State\":\"Unchanged\", \"Guid\":\"00000000-0000-0000-0000-000000000000\", \"Id\":\"39\", \"Name\":\"Test org\", \"ShortName\":\"Test\" } } } }"
    27. JsonObject root = new JsonParser().parse(json).getAsJsonObject()
    28. JsonObject lightObjectSet = root.get("LightObjectSet").getAsJsonObject()
    29. JsonObject objects = lightObjectSet.get("Objects").getAsJsonObject()
    30. JsonElement org = objects.get("Org")
    31. Gson g = new Gson()
    32. Org o = g.fromJson(org, Org.class)
    33. System.out.print(o)
    34. }
    35. }

    • See Also (1)
    1. Convert JSON to HashMap using Gson in Java

      I used it for Hashtable_**. Replace KioskStatusResource to your class and Integer to your key class. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static Hashtable<Integer, KioskStatusResource> parseModifued(String json) { JsonObject object = (JsonObject) new com.google.gson.JsonParser().parse(json)
      2. Set<Map.Entry<String, JsonElement>> set = object.entrySet()
      3. Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator()
      4. Hashtable<Integer, KioskStatusResource> map = new Hashtable<Integer, KioskStatusResource>()
      5. while (iterator.hasNext()) { Map.Entry<String, JsonElement> entry = iterator.next()
      6. Integer key = Integer.parseInt(entry.getKey())
      7. KioskStatusResource value = new Gson().fromJson(entry.getValue(), KioskStatusResource.class)
      8. if (value != null) { map.put(key, value)
      9. } } return map
      10. }

  28. GSON fromJSON Deserialization with Conditional to Exclude Specific Object Instances

    I think that best way of doing it is through custom deserialization. Here is what I mean you can copy&paste&try immediately) . .. details

    1. package stackoverflow.questions.q19912055
    2. import com.google.gson.*
    3. import com.google.gson.reflect.TypeToken
    4. import java.lang.reflect.Type
    5. import java.util.*
    6. import stackoverflow.questions.q17853533.*
    7. public class Q19912055 {
    8. class Region {
    9. String id
    10. String name
    11. String color
    12. Integer hasResorts
    13. @Override
    14. public String toString() {
    15. return "Region [id="
    16. + id
    17. + ", name="
    18. + name
    19. + ", color="
    20. + color
    21. + ", hasResorts="
    22. + hasResorts
    23. + "]"
    24. }
    25. }
    26. static class RegionDeserializer implements JsonDeserializer<List<Region>> {
    27. public List<Region> deserialize(
    28. JsonElement json, Type typeOfT, JsonDeserializationContext context)
    29. throws JsonParseException {
    30. if (json == null) return null
    31. ArrayList<Region> al = new ArrayList<Region>()
    32. for (JsonElement e : json.getAsJsonArray()) {
    33. boolean deserialize = e.getAsJsonObject().get("hasResorts").getAsInt() > 0
    34. if (deserialize) al.add((Region) context.deserialize(e, Region.class))
    35. }
    36. return al
    37. }
    38. }
    39. /** * @param args */
    40. public static void main(String[] args) {
    41. String json =
    42. " [ "
    43. + " { "
    44. + " \"id\": \"69\", "
    45. + " \"name\": \"North Carolina Coast\", "
    46. + " \"color\": \"#01162c\", "
    47. + " \"hasResorts\": 1 "
    48. + " }, "
    49. + " { "
    50. + " \"id\": \"242\", "
    51. + " \"name\": \"North Carolina Inland\", "
    52. + " \"color\": \"#01162c\", "
    53. + " \"hasResorts\": 0 "
    54. + " }, "
    55. + " { "
    56. + " \"id\": \"17\", "
    57. + " \"name\": \"North Carolina Mountains\", "
    58. + " \"color\": \"#01162c\", "
    59. + " \"hasResorts\": 1 "
    60. + " }, "
    61. + " { "
    62. + " \"id\": \"126\", "
    63. + " \"name\": \"Outer Banks\", "
    64. + " \"color\": \"#01162c\", "
    65. + " \"hasResorts\": 1 "
    66. + " } "
    67. + " ] "
    68. Type listType = new TypeToken<ArrayList<Region>>() {}.getType()
    69. List<Region> allRegions = new Gson().fromJson(json, listType)
    70. System.out.println(allRegions)
    71. GsonBuilder builder = new GsonBuilder()
    72. builder.registerTypeAdapter(listType, new RegionDeserializer())
    73. Gson gson2 = builder.create()
    74. List<Region> regionsHaveResort = gson2.fromJson(json, listType)
    75. System.out.println(regionsHaveResort)
    76. }
    77. }

    Positive Reactions
    1. Thanks!.
    Other Reactions
    1. That's the stuff.

    • See Also (1)
    1. Gson Expected BEGIN_ARRAY but was STRING at line 1 column 62

      As already Brain noted you have a array of objects so you need to convert this by your own with a custom guide#TOC-Writing-a-Deserializer deserializer . Here is an example implementation . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class q16380367 {
      2. final class CFS {
      3. public HashMap<String, String> files = new HashMap<String, String>()
      4. public ArrayList<String> directories = new ArrayList<String>()
      5. }
      6. public static void main(String[] args) {
      7. new q16380367()
      8. }
      9. public q16380367() {
      10. String JSON_STRING =
      11. "{\"directories\" : [\"folder1\", \"folder1/folder2\"], \"files\" : [{\"folder1\" : \"file.txt\"}, {\"folder1/folder2\" : \"file.cfg\"}]}"
      12. Gson gson =
      13. new GsonBuilder()
      14. .registerTypeAdapter(
      15. new TypeToken<HashMap<String, String>>() {}.getType(), new CfsDeserializer())
      16. .create()
      17. CFS foo = gson.fromJson(JSON_STRING, CFS.class)
      18. }
      19. private final class CfsDeserializer implements JsonDeserializer<HashMap<String, String>> {
      20. @Override
      21. public HashMap<String, String> deserialize(
      22. JsonElement json, Type typeOfT, JsonDeserializationContext context)
      23. throws JsonParseException {
      24. HashMap<String, String> data = new HashMap<String, String>()
      25. JsonArray list = json.getAsJsonArray()
      26. for (JsonElement e : list) {
      27. Set<Entry<String, JsonElement>> entries = e.getAsJsonObject().entrySet()
      28. for (Entry<String, JsonElement> entry : entries) {
      29. data.put(entry.getKey(), entry.getValue().getAsString())
      30. }
      31. }
      32. return data
      33. }
      34. }
      35. }

  29. How to put JSON information in an array to use it for displaying in ListView

    The basic idea is you make an object that relates directly to your json objects after you have this you can easily store your data in java objects and use it however you like. GSON example Where MyCustomClass would contain the variables id type and data. .. details

    1. Gson gson = new Gson()
    2. MyCustomClass obj2 = gson.fromJson(json, MyCustomClass.class)

    Positive Reactions
    1. Like one of the JSON array entry won't have the data label or any values there.
    2. Do you mean that your value is just an empty string after parsing the JSON?
    3. You can add a property to a json object by doing something like this: jsonObject.put("data", "some value"); And you could do this after checking the isNull I mentioned before.
    4. I would recommend using Androids AsyncTask to run your network call on a new thread.
    5. But like I said, this may be more than what you need for your application.
    6. jsonObject.isNull("data"); This will return true if there is no mapping for data.
    Negative Reactions
    1. So you can only try to grab a value for data if that returns false.
    Other Reactions
    1. Yeah that would be one approach to do it, if you are looking to expand on this and maybe persist the data you may want to look into storing your data in a database on the phone once you receive it.
    2. What if some of the entry is NO DATA, can I dummy fill it with data?
    3. You can use the isNull method available in the JSONObject to check if there is data there.
    4. I was able to receive the json text and now to extract it.
    5. Eclipse gives me a warning: 11-11 15:26:11.433: W/System.err(9054): org.json.JSONException: No value for dataI am wondering if the any of the label is missing, just fill it with dummy data.
    6. URL_http://developer.android.com/reference/android/os/AsyncTask.html .
    7. jsonString is which variable in my class?
    8. This would be the result you get back from your network call.
    9. Does that help?
    10. Here is my Pastebin: URL_http://pastebin.com/260jvLcx (I am opening up a chat for this).
    11. I have 7 entries but once it received a blank entry it skips everything after.
    12. Also all networking needs to be done on a separate thread and not the UI thread.
    13. let us [continue this discussion in chat]( URL_http://chat.stackoverflow.com/rooms/40980/discussion-between-sikni8-and - dejanristic).
    14. If you look at my full program code, maybe you will have a better understanding of it?
    15. This way where ever you are in your app you could do a query to retrieve the data.
    16. I am thinking I can put it in a Public array which can be accessible by any of the fragments within the activity.
    17. Is there anyway to fill it with dummy, or it just won't be allowed to do that?

    • See Also (2)
    1. Maximum as3 adobe JSON string length

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. // declaring varsprivate var _socket:Socket
      2. private var _cache: String = ""
      3. // adding EventListener_socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData)
      4. private function onSocketData(e: Event):void{ // take the incoming data from socket var fromServer: ByteArray = new ByteArray
      5. while (_socket.bytesAvailable) { _socket.readBytes(fromServer)
      6. } var receivedToString: String = fromServer.toString()
      7. _cache += receivedToString
      8. if (receivedToString.length == 0) return
      9. // nothing to parse // convert that long string to the Vector of JSONs // here is very small and not fail-safe alghoritm of detecting separate JSONs in one long String var jsonPart: String = ""
      10. var jsonVector: Vector.<String> = new Vector.<String>
      11. var bracketsCount: int = 0
      12. var endOfLastJson: int = 0
      13. for (var i: int = 0
      14. i < _cache.length
      15. i++) { if (_cache.charAt(i) == "{") bracketsCount += 1
      16. if (bracketsCount > 0) jsonPart = jsonPart.concat(_cache.charAt(i))
      17. if (_cache.charAt(i) == "}") { bracketsCount -= 1
      18. if (bracketsCount == 0) { jsonVector.push(jsonPart)
      19. jsonPart = ""
      20. endOfLastJson = i
      21. } } } // removing part that isn't needed anymore if (jsonVector.length > 0) { _cache = _cache.substr(endOfLastJson + 1)
      22. } for each (var part: String in jsonVector) { trace("RECEIVED: " + part)
      23. // voila! here is the full received JSON }}

    2. How to Parse the JSON String Andriod

      What you have to do is to name every element of the json with a unique name so as to fetch it. such as . details

      Reactions - Positive 0, Negative 0, Others 0

      1. {"result": ["result1":["result2":{"0":" ","title":" Technical Support Analyst in Noida","1":" ","Company Name":" Oracle","2":" ","Category":"Fresher","3":" ","Job Type":"Full Time","4":" ","Location":"Noida","5":" ","Job Qualification":"BE\/BTch\/Bsc\/Others","6":" ","Job Experience":"Freshers","7":" ","Job postdate":"2013-6-05","8":" "}]]}

      Other Reactions
      1. where did you read that?

  30. Java List of custom objects inside response object not populated with GSON unmarshaller

    Let me know if you need more information about that. This is execution result . .. details

    1. package stackoverflow.questions.q19817221
    2. import com.google.gson.Gson
    3. import java.util.*
    4. public class Q19817221 {
    5. public class ListWrapper {
    6. private Map list
    7. private Map status
    8. private Map batch
    9. private Object extractValue(Map m) {
    10. return m.get("$")
    11. }
    12. public Integer getBatch() {
    13. return Integer.valueOf((String) extractValue(batch))
    14. }
    15. public Object getValueFromList(String key) {
    16. try {
    17. Map m = (Map) list.get(key)
    18. if (m != null) return extractValue(m)
    19. } catch (Exception e) {
    20. return list.get(key)
    21. }
    22. return null
    23. }
    24. public Object getValueFromList(String secondLevelKey, String key) {
    25. Map secondLevelMap = (Map) list.get(secondLevelKey)
    26. try {
    27. Map m = (Map) secondLevelMap.get(key)
    28. if (m != null) return extractValue(m)
    29. } catch (Exception e) {
    30. return list.get(key)
    31. }
    32. return null
    33. }
    34. }
    35. public class Container {
    36. public ListWrapper ListWrapper
    37. }
    38. /** * @param args */
    39. public static void main(String[] args) {
    40. String json =
    41. "{\"ListWrapper\":{\"batch\":{\"$\":\"0\"},\"list\":{\"@xmlns\":{\"xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},\"@xsi:type\":\"fidsUsers\",\"createdBy\":{\"$\":\"administrator\"},\"createdWhen\":{\"$\":\"2013-02-25T17:29:19-05:00\"},\"endDate\":{\"$\":\"2016-10-28T00:00:00-04:00\"},"
    42. + "\"isDisabled\":{\"$\":\"N\"},\"previousPasswords\":{\"$\":\"HXQDa4WxTdBmZtvhMVTgnw==@@@@zW6bdHkKdMN2p6CgRNjNHA==@@@@Sim7JN3kaHoXnh3KUS2++Q==@@@@Emz7zU0Wrm0lyb/K522O5A==@@ZirxzRl28JqfjOzIaMzAog==\"},"
    43. + "\"primaryKey\":{\"$\":\"David\"},\"pswdChgDate\":{\"$\":\"2013-07-12T08:27:46-04:00\"},\"pswdCount\":{\"$\":\"0\"},\"roleId\":{\"$\":\"Admin\"},\"roleIdFidsRoles\":{\"globalAccess\":{\"$\":\"Y\"},\"primaryKey\":{\"$\":\"Admin\"},\"roleDesc\":{\"$\":\"Administrator\"},\"roleId\":{\"$\":\"Admin\"},"
    44. + "\"updatedBy\":{\"$\":\"David\"}},\"startDate\":{\"$\":\"1992-07-28T00:00:00-04:00\"},\"updatedBy\":{\"$\":\"David\"},\"updatedWhen\":{\"$\":\"2013-10-02T10:46:31-04:00\"},\"userId\":{\"$\":\"David\"},\"userName\":{\"$\":\"David3\"},\"userPassword\":{\"$\":\"HXQDa4WxTdBmZtvhMVTgnw==\"}},\"status\":{\"$\":\"Success\"}}}"
    45. Container c = new Gson().fromJson(json, Container.class)
    46. ListWrapper lw = c.ListWrapper
    47. System.out.println("batch:" + lw.getBatch())
    48. System.out.println("createdBy:" + lw.getValueFromList("createdBy"))
    49. System.out.println("@xsi:type: " + lw.getValueFromList("@xsi:type"))
    50. System.out.println(
    51. "roleIdFidsRoles\\primaryKey: " + lw.getValueFromList("roleIdFidsRoles", "primaryKey"))
    52. }
    53. }

    Positive Reactions
    1. If both servers have a jar containing your classes is quite simple to do.
    2. About your current question, you asked how to deserialize and this is, to my knowledge, the best option you have.
    Negative Reactions
    1. But if I have different objects in the list, now it becomes difficult to use strings to find it.
    2. Of course is not an object easy to handle, once you got it.
    Other Reactions
    1. Copy and paste your JSON into URL_http://json.parser.online.fr / for example to "navigate" it.
    2. Do you think if I created the JSON just with GSON it would serialize correctly down to a list, so that I could deserialize it correctly?
    3. So, again, if you can code both side of the servers, use Gson to serialize and deserialize passing your classes.
    4. If you have the same technology on both servers (Java I mean), you can serialize with Gson from one side and deserialize with Gson again on the other.
    5. I really do not know badgefish, so my comment will be limited to what I know: Gson.
    6. If you are in this case, I suggest you to use Gson only.
    7. You said that the list I have has actually be come a map when it was serialized.
    8. I'm using badgerfish(jettison) on a RestEasy service to make the json from JAXB xml.
    9. About this question, Gson produces a map since a map is what is serialized in the Json string.

    • See Also (1)
    1. I am new to JSON , is there any way to validate a json- key value pair

      not as part of some larger application) then try the jsonlint.com service. Sample syntax-check with Gson using lombok Output Err stderr Out stdout) . details

      Reactions - Positive 1, Negative 0, Others 0

      1. package com.stackoverflow.so13701022
      2. import com.google.gson.Gson
      3. import com.google.gson.GsonBuilder
      4. import com.google.gson.JsonSyntaxException
      5. import com.google.gson.annotations.SerializedName
      6. import lombok.Data
      7. public class CheckJson {
      8. @Data
      9. private static class LineOfBusiness {
      10. @SerializedName("LOB1")
      11. private String lob1
      12. @SerializedName("LOB2")
      13. private String lob2
      14. @SerializedName("LOB3")
      15. private String lob3
      16. @SerializedName("LOB4")
      17. private String lob4
      18. }
      19. @Data
      20. private static class Market {
      21. @SerializedName("MKTID001")
      22. private String mktid001
      23. @SerializedName("MKTID002")
      24. private String mktid002
      25. @SerializedName("LOB3")
      26. private String lob3
      27. @SerializedName("LOB4")
      28. private String lob4
      29. }
      30. private static final String ONE =
      31. "{"
      32. + " LOB1 : \"LOBAppType=sadfsd\","
      33. + " LOB2 : \"LOBAppType=asdf\","
      34. + " LOB3 : \"LOBAppType=asdf}"
      35. + " LOB4 : \"LOBAppType=sdf\","
      36. + "}"
      37. // I corrected this one on purpose private static final String TWO = "{" + " MKTID001 :\"MarketName=US||Descr=USA\"," + " MKTID002 :\"MarketName=JP||Descr=Japan\"," + " LOB3 : \"LOBAppType=asdf\"," + " LOB4 : \"LOBAppType=sdf\"" + "}"
      38. public static void main(String[] args) {
      39. final Gson gson = new GsonBuilder().create()
      40. System.out.println(tryParse(gson, ONE, LineOfBusiness.class))
      41. System.out.println(tryParse(gson, TWO, Market.class))
      42. }
      43. private static <T> T tryParse(Gson gson, String what, Class<T> clazz) {
      44. try {
      45. return gson.fromJson(what, clazz)
      46. } catch (final JsonSyntaxException e) {
      47. System.err.println(e)
      48. }
      49. return null
      50. }
      51. }

      Positive Reactions
      1. Is there any way to do it dynamically.
      Other Reactions
      1. actually i am loading these objects from a js file.

  31. Parsing Json Array resulting in This is not a JSON Array exception

    None .. details

    1. RootElement root = gson.fromJson(jsonReader, RootElement.class)
    2. System.out.println(root.FoodItemData)

  32. Why doesn&#39;t Java using GSON serialize my object into an appropriate JSON format?

    By default Gson will not give you the JSON string you want you have to customize Gson with a specific serializer for you enum. Here it is And this how to use it. .. details

    1. package stackoverflow.questions.q19715374
    2. import com.google.gson.*
    3. import java.lang.reflect.Type
    4. import java.util.*
    5. public class CustomSerializer implements JsonSerializer<Error> {
    6. @Override
    7. public JsonElement serialize(Error error, Type typeOfSrc, JsonSerializationContext context) {
    8. if (error == null) return null
    9. else {
    10. JsonObject jo = new JsonObject()
    11. jo.add("code", new JsonPrimitive(error.code))
    12. jo.add("message", new JsonPrimitive(error.message))
    13. return jo
    14. }
    15. }
    16. }

    Other Reactions
    1. How do I write a deserializer ?
    2. I did an edit to my answer.

  33. How to use jQuery to post JSON data to a Struts2 Action class

    None .. details

    1. var data = JSON.stringify(dataObj)
    2. $.ajax({ url: "Update", type: "post", data: "data:"+data, dataType: 'json', contentType:"application/json
    3. charset=utf-8", success : function(){ alert("You made it!")
    4. }})

    • See Also (1)
    1. Need Json results in a Table Format

      The class Data just represents one row of your HTML table and the database table). Now here's how you can load a table with help of ajax/1900796#1900796 jQuery.getJSON The tableid of course denotes the idof the HTML table element in question. details

      Reactions - Positive 0, Negative 0, Others 0

      1. $.getJSON("http://example.com/json", function(list) { var table = $('#tableid')
      2. $.each(list, function(index, data) { $('<tr>').appendTo(table) .append($('<td>').text(data.id)) .append($('<td>').text(data.name)) .append($('<td>').text(data.value))
      3. })
      4. })

      Other Reactions
      1. +1 up-vote.

  34. How to convert complex Java object into JSON

    None .. details

    1. public static void main(String[] args) { Gson gson = new Gson()
    2. JsonTest test = new JsonTest("naveen", 20, 20000)
    3. JsonTest test2 = new JsonTest("parveen", 20, 20000)
    4. JsonTest test3 = new JsonTest("pawan", 20, 20000)
    5. JsonTest test4 = new JsonTest("anil", 20, 20000)
    6. List<JsonTest> list = new ArrayList<JsonTest>()
    7. list.add(test)
    8. list.add(test2)
    9. list.add(test3)
    10. list.add(test4)
    11. ListRow<JsonTest> dataList = new ListRow<JsonTest>(2, 2, list)
    12. Type type = new TypeToken<ListRow<JsonTest>>() {}.getType()
    13. System.out.println(gson.toJson(dataList, type))
    14. }

    • See Also (11)
    1. How to deserialize a JSON file into an ArrayList with nested classes?

      You can simply achieve this with Gson. With this result I have added standard toString methods) Since you are asking about a JSON file ie a text file that contains a JSON string please make reference to how-to-create-a-java-string-from-the-contents-of-a-file How-to-create-a Java-String-from-the-contents-of-a-file question for loading a file into a string. details

      Reactions - Positive 0, Negative 0, Others 0

      1. package stackoverflow.questions.q18932252
      2. import com.google.gson.Gson
      3. import com.google.gson.reflect.TypeToken
      4. import java.lang.reflect.Type
      5. import java.util.*
      6. public class Q18932252 {
      7. public static void main(String[] args) {
      8. String json =
      9. "[{\"b\" : {\"a\": \"Hello!\"}}, {\"b\" : {\"a\": \"Hi!\"}}, {\"b\" : {\"a\": \"Hello2!\"}}]"
      10. Type listOfA = new TypeToken<List<A>>() {}.getType()
      11. Gson g = new Gson()
      12. ArrayList<A> result = g.fromJson(json, listOfA)
      13. System.out.println(result)
      14. }
      15. }

    2. Unable to parse a complex json

      Just use a library that handles the mapping for you. Jackson or in the example below GSON makes this a breeze Running this Main class produces . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.annotations.SerializedName
      3. import com.google.gson.reflect.TypeToken
      4. import java.util.*
      5. public class Main {
      6. public static void main(String[] args) {
      7. Gson gson = new Gson()
      8. List<Album> albums = gson.fromJson(albumsJson, new TypeToken<ArrayList<Album>>() {}.getType())
      9. for (Album album : albums) {
      10. System.out.println(album)
      11. }
      12. List<SongList> songs =
      13. gson.fromJson(songListJson, new TypeToken<ArrayList<SongList>>() {}.getType())
      14. for (SongList song : songs) {
      15. System.out.println(song)
      16. }
      17. }
      18. class Album {
      19. @SerializedName("albumid")
      20. String albumId
      21. String name
      22. @SerializedName("songs_count")
      23. String songsCount
      24. @Override
      25. public String toString() {
      26. return "Album{"
      27. + "albumId='"
      28. + albumId
      29. + '\''
      30. + ", name='"
      31. + name
      32. + '\''
      33. + ", songsCount='"
      34. + songsCount
      35. + '\''
      36. + '}'
      37. }
      38. }
      39. class SongList {
      40. @SerializedName("albumid")
      41. String albumId
      42. String album
      43. List<Song> songs
      44. @Override
      45. public String toString() {
      46. return "SongList{"
      47. + "albumId='"
      48. + albumId
      49. + '\''
      50. + ", album='"
      51. + album
      52. + '\''
      53. + ", songs="
      54. + songs
      55. + '}'
      56. }
      57. }
      58. class Song {
      59. String id
      60. String name
      61. String duration
      62. @Override
      63. public String toString() {
      64. return "Song{"
      65. + "id='"
      66. + id
      67. + '\''
      68. + ", name='"
      69. + name
      70. + '\''
      71. + ", duration='"
      72. + duration
      73. + '\''
      74. + '}'
      75. }
      76. }
      77. static String albumsJson =
      78. "[\n"
      79. + " { \"albumid\": \"1\",\n"
      80. + " \"name\":\"127 Hours\",\n"
      81. + " \"songs_count\":\"14\"\n"
      82. + " },\n"
      83. + " { \"albumid\": \"2\",\n"
      84. + " \"name\":\"Adele 21\",\n"
      85. + " \"songs_count\":\"11\"\n"
      86. + " },\n"
      87. + " { \"albumid\": \"3\",\n"
      88. + " \"name\":\"Lana Del Rey - Born to Die\",\n"
      89. + " \"songs_count\":\"12\"\n"
      90. + " },\n"
      91. + " { \"albumid\": \"4\",\n"
      92. + " \"name\":\"Once\",\n"
      93. + " \"songs_count\":\"13\"\n"
      94. + " },\n"
      95. + " { \"albumid\": \"5\",\n"
      96. + " \"name\":\"Away We Go\",\n"
      97. + " \"songs_count\":\"13\"\n"
      98. + " },\n"
      99. + " { \"albumid\": \"6\",\n"
      100. + " \"name\":\"Eminem Curtain Call\",\n"
      101. + " \"songs_count\":\"14\"\n"
      102. + " },\n"
      103. + " { \"albumid\": \"7\",\n"
      104. + " \"name\":\"Bad Meets Evil Eminem\",\n"
      105. + " \"songs_count\":\"11\"\n"
      106. + " },\n"
      107. + " { \"albumid\": \"8\",\n"
      108. + " \"name\":\"Safe Trip Home\",\n"
      109. + " \"songs_count\":\"11\"\n"
      110. + " },\n"
      111. + " { \"albumid\": \"9\",\n"
      112. + " \"name\":\"No Angel\",\n"
      113. + " \"songs_count\":\"12\"\n"
      114. + " }\n"
      115. + "]"
      116. static String songListJson =
      117. "[\n"
      118. + " {\n"
      119. + " \"albumid\": \"1\",\n"
      120. + " \"album\": \"127 Hours\",\n"
      121. + " \"songs\": [\n"
      122. + " {\n"
      123. + " \"id\": \"1\",\n"
      124. + " \"name\": \"Never Hear Surf Music Again\",\n"
      125. + " \"duration\": \"5:52\"\n"
      126. + " },\n"
      127. + " {\n"
      128. + " \"id\": \"2\",\n"
      129. + " \"name\": \"The Canyon\",\n"
      130. + " \"duration\": \"3:01\"\n"
      131. + " },\n"
      132. + " {\n"
      133. + " \"id\": \"3\",\n"
      134. + " \"name\": \"Liberation Begins\",\n"
      135. + " \"duration\": \"2:14\"\n"
      136. + " },\n"
      137. + " {\n"
      138. + " \"id\": \"4\",\n"
      139. + " \"name\": \"Touch of the Sun\",\n"
      140. + " \"duration\": \"4:39\"\n"
      141. + " },\n"
      142. + " {\n"
      143. + " \"id\": \"5\",\n"
      144. + " \"name\": \"Lovely Day\",\n"
      145. + " \"duration\": \"4:16\"\n"
      146. + " },\n"
      147. + " {\n"
      148. + " \"id\": \"6\",\n"
      149. + " \"name\": \"Ca Plane Pour Moi\",\n"
      150. + " \"duration\": \"3:00\"\n"
      151. + " },\n"
      152. + " {\n"
      153. + " \"id\": \"7\",\n"
      154. + " \"name\": \"Liberation In A Dream\",\n"
      155. + " \"duration\": \"4:06\"\n"
      156. + " },\n"
      157. + " {\n"
      158. + " \"id\": \"8\",\n"
      159. + " \"name\": \"If You Love Me (Really Love Me)\",\n"
      160. + " \"duration\": \"3:27\"\n"
      161. + " },\n"
      162. + " {\n"
      163. + " \"id\": \"9\",\n"
      164. + " \"name\": \"Acid Darbari\",\n"
      165. + " \"duration\": \"4:21\"\n"
      166. + " },\n"
      167. + " {\n"
      168. + " \"id\": \"10\",\n"
      169. + " \"name\": \"R.I.P.\",\n"
      170. + " \"duration\": \"5:11\"\n"
      171. + " },\n"
      172. + " {\n"
      173. + " \"id\": \"11\",\n"
      174. + " \"name\": \"Festival\",\n"
      175. + " \"duration\": \"9:26\"\n"
      176. + " },\n"
      177. + " {\n"
      178. + " \"id\": \"12\",\n"
      179. + " \"name\": \"If I Rise\",\n"
      180. + " \"duration\": \"4:38\"\n"
      181. + " },\n"
      182. + " {\n"
      183. + " \"id\": \"13\",\n"
      184. + " \"name\": \"Liberation\",\n"
      185. + " \"duration\": \"3:11\"\n"
      186. + " },\n"
      187. + " {\n"
      188. + " \"id\": \"14\",\n"
      189. + " \"name\": \"Nocturne No. 2 in E flat\",\n"
      190. + " \"duration\": \"4:01\"\n"
      191. + " }\n"
      192. + " ]\n"
      193. + " },\n"
      194. + " {\n"
      195. + " \"albumid\": \"2\",\n"
      196. + " \"album\": \"Adele 21\",\n"
      197. + " \"songs\": [\n"
      198. + " {\n"
      199. + " \"id\": \"1\",\n"
      200. + " \"name\": \"Rolling In The Deep\",\n"
      201. + " \"duration\": \"03:48\"\n"
      202. + " },\n"
      203. + " {\n"
      204. + " \"id\": \"2\",\n"
      205. + " \"name\": \"Rumour Has It\",\n"
      206. + " \"duration\": \"03:43\"\n"
      207. + " },\n"
      208. + " {\n"
      209. + " \"id\": \"3\",\n"
      210. + " \"name\": \"Turning Tables\",\n"
      211. + " \"duration\": \"04:10\"\n"
      212. + " },\n"
      213. + " {\n"
      214. + " \"id\": \"4\",\n"
      215. + " \"name\": \"Don\\u2019t You Remember\",\n"
      216. + " \"duration\": \"04:03\"\n"
      217. + " },\n"
      218. + " {\n"
      219. + " \"id\": \"5\",\n"
      220. + " \"name\": \"Set Fire To The Rain\",\n"
      221. + " \"duration\": \"04:02\"\n"
      222. + " },\n"
      223. + " {\n"
      224. + " \"id\": \"6\",\n"
      225. + " \"name\": \"He Won\\u2019t Go\",\n"
      226. + " \"duration\": \"04:38\"\n"
      227. + " },\n"
      228. + " {\n"
      229. + " \"id\": \"7\",\n"
      230. + " \"name\": \"Take It All\",\n"
      231. + " \"duration\": \"03:48\"\n"
      232. + " },\n"
      233. + " {\n"
      234. + " \"id\": \"8\",\n"
      235. + " \"name\": \"I\\u2019ll Be Waiting\",\n"
      236. + " \"duration\": \"04:01\"\n"
      237. + " },\n"
      238. + " {\n"
      239. + " \"id\": \"9\",\n"
      240. + " \"name\": \"One And Only\",\n"
      241. + " \"duration\": \"05:48\"\n"
      242. + " },\n"
      243. + " {\n"
      244. + " \"id\": \"10\",\n"
      245. + " \"name\": \"Lovesong\",\n"
      246. + " \"duration\": \"05:16\"\n"
      247. + " },\n"
      248. + " {\n"
      249. + " \"id\": \"11\",\n"
      250. + " \"name\": \"Someone Like You\",\n"
      251. + " \"duration\": \"04:45\"\n"
      252. + " }\n"
      253. + " ]\n"
      254. + " },\n"
      255. + " {\n"
      256. + " \"albumid\": \"3\",\n"
      257. + " \"album\": \"Lana Del Rey - Born to Die\",\n"
      258. + " \"songs\": [\n"
      259. + " {\n"
      260. + " \"id\": \"1\",\n"
      261. + " \"name\": \"Born to Die\",\n"
      262. + " \"duration\": \"4:46\"\n"
      263. + " },\n"
      264. + " {\n"
      265. + " \"id\": \"2\",\n"
      266. + " \"name\": \"Off to the Races\",\n"
      267. + " \"duration\": \"5:00\"\n"
      268. + " },\n"
      269. + " {\n"
      270. + " \"id\": \"3\",\n"
      271. + " \"name\": \"Blue Jeans\",\n"
      272. + " \"duration\": \"3:29\"\n"
      273. + " },\n"
      274. + " {\n"
      275. + " \"id\": \"4\",\n"
      276. + " \"name\": \"Video Games\",\n"
      277. + " \"duration\": \"4:42\"\n"
      278. + " },\n"
      279. + " {\n"
      280. + " \"id\": \"5\",\n"
      281. + " \"name\": \"Diet Mountain Dew\",\n"
      282. + " \"duration\": \"3:43\"\n"
      283. + " },\n"
      284. + " {\n"
      285. + " \"id\": \"6\",\n"
      286. + " \"name\": \"National Anthem\",\n"
      287. + " \"duration\": \"3:51\"\n"
      288. + " },\n"
      289. + " {\n"
      290. + " \"id\": \"7\",\n"
      291. + " \"name\": \"Dark Paradise\",\n"
      292. + " \"duration\": \"4:03\"\n"
      293. + " },\n"
      294. + " {\n"
      295. + " \"id\": \"8\",\n"
      296. + " \"name\": \"Radio\",\n"
      297. + " \"duration\": \"3:35\"\n"
      298. + " },\n"
      299. + " {\n"
      300. + " \"id\": 9,\n"
      301. + " \"name\": \"Carmen\",\n"
      302. + " \"duration\": \"4:09\"\n"
      303. + " },\n"
      304. + " {\n"
      305. + " \"id\": \"10\",\n"
      306. + " \"name\": \"Million Dollar Man\",\n"
      307. + " \"duration\": \"3:50\"\n"
      308. + " },\n"
      309. + " {\n"
      310. + " \"id\": \"11\",\n"
      311. + " \"name\": \"Summertime Sadness\",\n"
      312. + " \"duration\": \"4:25\"\n"
      313. + " },\n"
      314. + " {\n"
      315. + " \"id\": \"12\",\n"
      316. + " \"name\": \"This Is What Makes Us Girls\",\n"
      317. + " \"duration\": \"4:00\"\n"
      318. + " }\n"
      319. + " ]\n"
      320. + " },\n"
      321. + " {\n"
      322. + " \"albumid\": \"4\",\n"
      323. + " \"album\": \"Once\",\n"
      324. + " \"songs\": [\n"
      325. + " {\n"
      326. + " \"id\": \"1\",\n"
      327. + " \"name\": \"Falling Slowly\",\n"
      328. + " \"duration\": \"4:05\"\n"
      329. + " },\n"
      330. + " {\n"
      331. + " \"id\": \"2\",\n"
      332. + " \"name\": \"If You Want Me\",\n"
      333. + " \"duration\": \"3:47\"\n"
      334. + " },\n"
      335. + " {\n"
      336. + " \"id\": \"3\",\n"
      337. + " \"name\": \"Broken Hearted Hoover Fixer Sucker Guy\",\n"
      338. + " \"duration\": \"0:52\"\n"
      339. + " },\n"
      340. + " {\n"
      341. + " \"id\": \"4\",\n"
      342. + " \"name\": \"When Your Mind's Made Up\",\n"
      343. + " \"duration\": \"3:42\"\n"
      344. + " },\n"
      345. + " {\n"
      346. + " \"id\": \"5\",\n"
      347. + " \"name\": \"Lies\",\n"
      348. + " \"duration\": \"3:58\"\n"
      349. + " },\n"
      350. + " {\n"
      351. + " \"id\": \"6\",\n"
      352. + " \"name\": \"Gold\",\n"
      353. + " \"duration\": \"3:59\"\n"
      354. + " },\n"
      355. + " {\n"
      356. + " \"id\": \"7\",\n"
      357. + " \"name\": \"The Hill\",\n"
      358. + " \"duration\": \"4:34\"\n"
      359. + " },\n"
      360. + " {\n"
      361. + " \"id\": \"8\",\n"
      362. + " \"name\": \"Fallen From The Sky\",\n"
      363. + " \"duration\": \"3:24\"\n"
      364. + " },\n"
      365. + " {\n"
      366. + " \"id\": \"9\",\n"
      367. + " \"name\": \"Leave\",\n"
      368. + " \"duration\": \"2:46\"\n"
      369. + " },\n"
      370. + " {\n"
      371. + " \"id\": \"10\",\n"
      372. + " \"name\": \"Trying To Pull Myself Away\",\n"
      373. + " \"duration\": \"3:35\"\n"
      374. + " },\n"
      375. + " {\n"
      376. + " \"id\": \"11\",\n"
      377. + " \"name\": \"All The Way Down\",\n"
      378. + " \"duration\": \"2:38\"\n"
      379. + " },\n"
      380. + " {\n"
      381. + " \"id\": \"12\",\n"
      382. + " \"name\": \"Once\",\n"
      383. + " \"duration\": \"3:37\"\n"
      384. + " },\n"
      385. + " {\n"
      386. + " \"id\": \"13\",\n"
      387. + " \"name\": \"Say It To Me Now\",\n"
      388. + " \"duration\": \"2:36\"\n"
      389. + " }\n"
      390. + " ]\n"
      391. + " },\n"
      392. + " {\n"
      393. + " \"albumid\": \"5\",\n"
      394. + " \"album\": \"Once\",\n"
      395. + " \"songs\": [\n"
      396. + " {\n"
      397. + " \"id\": \"1\",\n"
      398. + " \"name\": \"Falling Slowly\",\n"
      399. + " \"duration\": \"4:05\"\n"
      400. + " },\n"
      401. + " {\n"
      402. + " \"id\": \"2\",\n"
      403. + " \"name\": \"If You Want Me\",\n"
      404. + " \"duration\": \"3:47\"\n"
      405. + " },\n"
      406. + " {\n"
      407. + " \"id\": \"3\",\n"
      408. + " \"name\": \"Broken Hearted Hoover Fixer Sucker Guy\",\n"
      409. + " \"duration\": \"0:52\"\n"
      410. + " },\n"
      411. + " {\n"
      412. + " \"id\": \"4\",\n"
      413. + " \"name\": \"When Your Mind's Made Up\",\n"
      414. + " \"duration\": \"3:42\"\n"
      415. + " },\n"
      416. + " {\n"
      417. + " \"id\": \"5\",\n"
      418. + " \"name\": \"Lies\",\n"
      419. + " \"duration\": \"3:58\"\n"
      420. + " },\n"
      421. + " {\n"
      422. + " \"id\": \"6\",\n"
      423. + " \"name\": \"Gold\",\n"
      424. + " \"duration\": \"3:59\"\n"
      425. + " },\n"
      426. + " {\n"
      427. + " \"id\": \"7\",\n"
      428. + " \"name\": \"The Hill\",\n"
      429. + " \"duration\": \"4:34\"\n"
      430. + " },\n"
      431. + " {\n"
      432. + " \"id\": \"8\",\n"
      433. + " \"name\": \"Fallen From The Sky\",\n"
      434. + " \"duration\": \"3:24\"\n"
      435. + " },\n"
      436. + " {\n"
      437. + " \"id\": \"9\",\n"
      438. + " \"name\": \"Leave\",\n"
      439. + " \"duration\": \"2:46\"\n"
      440. + " },\n"
      441. + " {\n"
      442. + " \"id\": \"10\",\n"
      443. + " \"name\": \"Trying To Pull Myself Away\",\n"
      444. + " \"duration\": \"3:35\"\n"
      445. + " },\n"
      446. + " {\n"
      447. + " \"id\": \"11\",\n"
      448. + " \"name\": \"All The Way Down\",\n"
      449. + " \"duration\": \"2:38\"\n"
      450. + " },\n"
      451. + " {\n"
      452. + " \"id\": \"12\",\n"
      453. + " \"name\": \"Once\",\n"
      454. + " \"duration\": \"3:37\"\n"
      455. + " },\n"
      456. + " {\n"
      457. + " \"id\": \"13\",\n"
      458. + " \"name\": \"Say It To Me Now\",\n"
      459. + " \"duration\": \"2:36\"\n"
      460. + " }\n"
      461. + " ]\n"
      462. + " },\n"
      463. + " {\n"
      464. + " \"albumid\": \"6\",\n"
      465. + " \"album\": \"Eminem Curtain Call\",\n"
      466. + " \"songs\": [\n"
      467. + " {\n"
      468. + " \"id\": \"1\",\n"
      469. + " \"name\": \"My Name Is\",\n"
      470. + " \"duration\": \"4:28\"\n"
      471. + " },\n"
      472. + " {\n"
      473. + " \"id\": \"2\",\n"
      474. + " \"name\": \"The Way I Am\",\n"
      475. + " \"duration\": \"4:51\"\n"
      476. + " },\n"
      477. + " {\n"
      478. + " \"id\": \"3\",\n"
      479. + " \"name\": \"Lose Yourself\",\n"
      480. + " \"duration\": \"5:21\"\n"
      481. + " },\n"
      482. + " {\n"
      483. + " \"id\": \"4\",\n"
      484. + " \"name\": \"Shake That\",\n"
      485. + " \"duration\": \"4:34\"\n"
      486. + " },\n"
      487. + " {\n"
      488. + " \"id\": \"5\",\n"
      489. + " \"name\": \"Sing For The Moment\",\n"
      490. + " \"duration\": \"5:40\"\n"
      491. + " },\n"
      492. + " {\n"
      493. + " \"id\": \"6\",\n"
      494. + " \"name\": \"Without Me\",\n"
      495. + " \"duration\": \"4:47\"\n"
      496. + " },\n"
      497. + " {\n"
      498. + " \"id\": \"7\",\n"
      499. + " \"name\": \"Like Toy Soldiers\",\n"
      500. + " \"duration\": \"4:51\"\n"
      501. + " },\n"
      502. + " {\n"
      503. + " \"id\": \"8\",\n"
      504. + " \"name\": \"The Real Slim Shady\",\n"
      505. + " \"duration\": \"4:44\"\n"
      506. + " },\n"
      507. + " {\n"
      508. + " \"id\": \"9\",\n"
      509. + " \"name\": \"Mockingbird\",\n"
      510. + " \"duration\": \"4:11\"\n"
      511. + " },\n"
      512. + " {\n"
      513. + " \"id\": \"10\",\n"
      514. + " \"name\": \"Guilty Conscience\",\n"
      515. + " \"duration\": \"3:19\"\n"
      516. + " },\n"
      517. + " {\n"
      518. + " \"id\": \"11\",\n"
      519. + " \"name\": \"Cleanin' Out My Closet\",\n"
      520. + " \"duration\": \"4:58\"\n"
      521. + " },\n"
      522. + " {\n"
      523. + " \"id\": \"12\",\n"
      524. + " \"name\": \"Just Lose It\",\n"
      525. + " \"duration\": \"4:08\"\n"
      526. + " },\n"
      527. + " {\n"
      528. + " \"id\": \"13\",\n"
      529. + " \"name\": \"When I'm Gone\",\n"
      530. + " \"duration\": \"4:40\"\n"
      531. + " },\n"
      532. + " {\n"
      533. + " \"id\": \"14\",\n"
      534. + " \"name\": \"Stan\",\n"
      535. + " \"duration\": \"6:21\"\n"
      536. + " }\n"
      537. + " ]\n"
      538. + " },\n"
      539. + " {\n"
      540. + " \"albumid\": \"7\",\n"
      541. + " \"album\": \"Bad Meets Evil Eminem\",\n"
      542. + " \"songs\": [\n"
      543. + " {\n"
      544. + " \"id\": \"1\",\n"
      545. + " \"name\": \"Lighters\",\n"
      546. + " \"duration\": \"5:21\"\n"
      547. + " },\n"
      548. + " {\n"
      549. + " \"id\": \"2\",\n"
      550. + " \"name\": \"Fast Lane\",\n"
      551. + " \"duration\": \"3:19\"\n"
      552. + " },\n"
      553. + " {\n"
      554. + " \"id\": \"3\",\n"
      555. + " \"name\": \"Above the Law\",\n"
      556. + " \"duration\": \"6:21\"\n"
      557. + " },\n"
      558. + " {\n"
      559. + " \"id\": \"4\",\n"
      560. + " \"name\": \"Welcome 2 Hell\",\n"
      561. + " \"duration\": \"4:34\"\n"
      562. + " },\n"
      563. + " {\n"
      564. + " \"id\": \"5\",\n"
      565. + " \"name\": \"Take from Me\",\n"
      566. + " \"duration\": \"4:51\"\n"
      567. + " },\n"
      568. + " {\n"
      569. + " \"id\": \"6\",\n"
      570. + " \"name\": \"The Reunion\",\n"
      571. + " \"duration\": \"4:44\"\n"
      572. + " },\n"
      573. + " {\n"
      574. + " \"id\": \"7\",\n"
      575. + " \"name\": \"A Kiss\",\n"
      576. + " \"duration\": \"3:19\"\n"
      577. + " },\n"
      578. + " {\n"
      579. + " \"id\": \"8\",\n"
      580. + " \"name\": \"Echo\",\n"
      581. + " \"duration\": \"6:21\"\n"
      582. + " },\n"
      583. + " {\n"
      584. + " \"id\": \"9\",\n"
      585. + " \"name\": \"Lighters\",\n"
      586. + " \"duration\": \"4:40\"\n"
      587. + " },\n"
      588. + " {\n"
      589. + " \"id\": \"10\",\n"
      590. + " \"name\": \"Living Proof\",\n"
      591. + " \"duration\": \"3:49\"\n"
      592. + " },\n"
      593. + " {\n"
      594. + " \"id\": \"11\",\n"
      595. + " \"name\": \"Loud Noises\",\n"
      596. + " \"duration\": \"3:19\"\n"
      597. + " }\n"
      598. + " ]\n"
      599. + " },\n"
      600. + " {\n"
      601. + " \"albumid\": \"8\",\n"
      602. + " \"album\": \"Safe Trip Home\",\n"
      603. + " \"songs\": [\n"
      604. + " {\n"
      605. + " \"id\": \"1\",\n"
      606. + " \"name\": \"Don't Believe in Love\",\n"
      607. + " \"duration\": \"3:52\"\n"
      608. + " },\n"
      609. + " {\n"
      610. + " \"id\": \"2\",\n"
      611. + " \"name\": \"Quiet Times\",\n"
      612. + " \"duration\": \"3:16\"\n"
      613. + " },\n"
      614. + " {\n"
      615. + " \"id\": \"3\",\n"
      616. + " \"name\": \"Never Want to Say It's Love\",\n"
      617. + " \"duration\": \"3:34\"\n"
      618. + " },\n"
      619. + " {\n"
      620. + " \"id\": \"4\",\n"
      621. + " \"name\": \"Grafton Street\",\n"
      622. + " \"duration\": \"5:56\"\n"
      623. + " },\n"
      624. + " {\n"
      625. + " \"id\": \"5\",\n"
      626. + " \"name\": \"It Comes And It Goes\",\n"
      627. + " \"duration\": \"3:26\"\n"
      628. + " },\n"
      629. + " {\n"
      630. + " \"id\": \"6\",\n"
      631. + " \"name\": \"Look No Further\",\n"
      632. + " \"duration\": \"3:15\"\n"
      633. + " },\n"
      634. + " {\n"
      635. + " \"id\": \"7\",\n"
      636. + " \"name\": \"Us 2 Little Gods\",\n"
      637. + " \"duration\": \"4:48\"\n"
      638. + " },\n"
      639. + " {\n"
      640. + " \"id\": \"8\",\n"
      641. + " \"name\": \"The Day Before The Day\",\n"
      642. + " \"duration\": \"4:12\"\n"
      643. + " },\n"
      644. + " {\n"
      645. + " \"id\": \"9\",\n"
      646. + " \"name\": \"Let's Do the Things We Normally Do\",\n"
      647. + " \"duration\": \"4:08\"\n"
      648. + " },\n"
      649. + " {\n"
      650. + " \"id\": \"10\",\n"
      651. + " \"name\": \"Burnin Love\",\n"
      652. + " \"duration\": \"4:10\"\n"
      653. + " },\n"
      654. + " {\n"
      655. + " \"id\": \"11\",\n"
      656. + " \"name\": \"Northern Skies\",\n"
      657. + " \"duration\": \"8:53\"\n"
      658. + " }\n"
      659. + " ]\n"
      660. + " },\n"
      661. + " {\n"
      662. + " \"albumid\": \"9\",\n"
      663. + " \"album\": \"No Angel\",\n"
      664. + " \"songs\": [\n"
      665. + " {\n"
      666. + " \"id\": \"1\",\n"
      667. + " \"name\": \"Here With Me\",\n"
      668. + " \"duration\": \"4:05\"\n"
      669. + " },\n"
      670. + " {\n"
      671. + " \"id\": \"2\",\n"
      672. + " \"name\": \"Hunter\",\n"
      673. + " \"duration\": \"3:55\"\n"
      674. + " },\n"
      675. + " {\n"
      676. + " \"id\": \"3\",\n"
      677. + " \"name\": \"Don't Think Of Me\",\n"
      678. + " \"duration\": \"4:32\"\n"
      679. + " },\n"
      680. + " {\n"
      681. + " \"id\": \"4\",\n"
      682. + " \"name\": \"My Lover's Gone\",\n"
      683. + " \"duration\": \"4:27\"\n"
      684. + " },\n"
      685. + " {\n"
      686. + " \"id\": \"5\",\n"
      687. + " \"name\": \"All You Want\",\n"
      688. + " \"duration\": \"3:53\"\n"
      689. + " },\n"
      690. + " {\n"
      691. + " \"id\": \"6\",\n"
      692. + " \"name\": \"Thank You\",\n"
      693. + " \"duration\": \"3:36\"\n"
      694. + " },\n"
      695. + " {\n"
      696. + " \"id\": \"7\",\n"
      697. + " \"name\": \"Honestly Ok\",\n"
      698. + " \"duration\": \"4:37\"\n"
      699. + " },\n"
      700. + " {\n"
      701. + " \"id\": \"8\",\n"
      702. + " \"name\": \"Slide\",\n"
      703. + " \"duration\": \"4:50\"\n"
      704. + " },\n"
      705. + " {\n"
      706. + " \"id\": \"9\",\n"
      707. + " \"name\": \"Isobel\",\n"
      708. + " \"duration\": \"3:55\"\n"
      709. + " },\n"
      710. + " {\n"
      711. + " \"id\": \"10\",\n"
      712. + " \"name\": \"I'm No Angel\",\n"
      713. + " \"duration\": \"3:55\"\n"
      714. + " },\n"
      715. + " {\n"
      716. + " \"id\": \"11\",\n"
      717. + " \"name\": \"My Life\",\n"
      718. + " \"duration\": \"2:59\"\n"
      719. + " },\n"
      720. + " {\n"
      721. + " \"id\": \"12\",\n"
      722. + " \"name\": \"Take My Hand\",\n"
      723. + " \"duration\": \"6:50\"\n"
      724. + " }\n"
      725. + " ]\n"
      726. + " }\n"
      727. + "]"
      728. }

    3. Deserializing Generic Types with GSON

      I didn't know about Type Erasure so thanks for pointing me on it. Method to deserialize generic collection . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Type listType = new TypeToken<ArrayList<YourClass>>() { }.getType()
      2. List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType)

      Other Reactions
      1. Not very... and it's copy pasted from John's link.
      2. how is this different from what was posted?

    4. deserializing a JSON object with multiple items inside it

      The data can also be viewed as a map of id's to attachments. And it can be deserialized as such This is actuall . details

      Reactions - Positive 1, Negative 2, Others 0

      1. final String jsonObj = new JSONObject(json).getJSONObject("attachments")
      2. final Gson gson = new Gson()
      3. final Map<String, Attachment> data = gson.fromJson(jsonObj.toString(), new TypeToken<Map<String, Attachment>>() { }.getType())
      4. final List<Attachment> attachments = new ArrayList<Attachment>(data.values())

      Positive Reactions
      1. thanks.
      Negative Reactions
      1. I think there is a misunderstanding here, either on my part or yours.
      2. had to do a little extra work, but your solution got me there.
      Other Reactions
      1. What is being represented here are not articles, but components of articles (namely attachments) which I'm trying to deserialize into fields of the Article instances you helped me with before..
      2. That's what I figured :) I'm trying what you suggested but am getting an error warning - Can only iterate over an array or an instance of java.lang.Iterable - on the for loop.
      3. see my edit if you're curious.
      4. Check out my edit (nothing substantial, basically replace Article with Attachment).
      5. You might have to tweak the code, I don't have access to an IDE atm.
      6. @drewmore4 - edited.
      7. @drewmore4 - indeed.

    5. deserialize json string with gson

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String lista = (String)request.getAttribute("lista")
      2. Gson gson = new Gson()
      3. Type listType = new TypeToken<ArrayList<Utente>>() {}.getType()
      4. ArrayList<Utente> users = new Gson().fromJson(lista, listType)

    6. Android SDK: Parsing JSON from URL using GSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public ArrayList<NewsItem> getNews(String url) { ArrayList<NewsItem> data = new ArrayList<NewsItem>()
      2. java.lang.reflect.Type arrayListType = new TypeToken<ArrayList<NewsItem>>(){}.getType()
      3. gson = new Gson()
      4. httpClient = WebServiceUtils.getHttpClient()
      5. try { HttpResponse response = httpClient.execute(new HttpGet(url))
      6. HttpEntity entity = response.getEntity()
      7. Reader reader = new InputStreamReader(entity.getContent())
      8. data = gson.fromJson(reader, arrayListType)
      9. } catch (Exception e) { Log.i("json array","While getting server response server generate error. ")
      10. } return data
      11. }

    7. Android SDK: Parsing JSON from URL using GSON

      That's the code I use working well for me). YourObject should be something like Regards. details

      Reactions - Positive 1, Negative 1, Others 0

      1. //Initialize the listType listType = new TypeToken<ArrayList<YourObject>>(){}.getType()
      2. //ParseList<YourObject> List= new Gson().fromJson(response, listType)

      Positive Reactions
      1. i'm not sure how to get the values themselves though, for example the "img- src" values should be added to one list and the "URL" values should be added to another list.
      Negative Reactions
      1. I had the same problem has you and I found not another way to do so.
      Other Reactions
      1. @user1417302 I'm not sure.
      2. right but I don't know why I need another class, is it not possible/quicker to just download the data and add it to an ArrayList?

    8. GSON turn an array of data objects into json - Android

      This should demonstrate exactly how to convert to/from Json how to reference lists etc. Test.java To compile it And finally to run it Note that if you're using Windows you'll have to switch with in the previous two commands After you run it you should see the following output Keep in mind that this is only a command line program to demonstrate how it works but the same principles apply within the Android environment referencing jar libs etc. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. import java.util.List
      3. public class Test {
      4. public static void main(
      5. String[]
      6. args) { // Initialize a list of type DataObject List<DataObject> objList = new ArrayList<DataObject>()
      7. objList.add(new DataObject(0, "zero"))
      8. objList.add(new DataObject(1, "one"))
      9. objList.add(new DataObject(2, "two"))
      10. // Convert the object to a JSON string String json = new Gson().toJson(objList)
      11. System.out.println(json)
      12. // Now convert the JSON string back to your java object Type type = new TypeToken<List<DataObject>>(){}.getType()
      13. List<DataObject> inpList = new Gson().fromJson(json, type)
      14. for (int i = 0 i < inpList.size() i++) {
      15. DataObject x = inpList.get(i)
      16. System.out.println(x)
      17. }
      18. }
      19. private static class DataObject {
      20. private int a
      21. private String b
      22. public DataObject(int a, String b) {
      23. this.a = a
      24. this.b = b
      25. }
      26. public String toString() {
      27. return "a = " + a + ", b = " + b
      28. }
      29. }
      30. }

    9. Getting a typed ArrayList from a JSON String in Java

      to avoid the exception u need to hav JsonArray inside the file like "key value". Here's a SSCCE that executes and that demonstrates exactly how to get back a typed ArrayList Output The fact that this code doesn't explode proves that the ArrayList is in fact typed correctly. details

      Reactions - Positive 2, Negative 2, Others 0

      1. public static void main(String args[]) { Gson gson = new Gson()
      2. List<Integer> outList = new ArrayList<Integer>()
      3. outList.add(1)
      4. outList.add(2)
      5. outList.add(3)
      6. String json = gson.toJson(outList)
      7. // This is how you tell gson about the generic type you want to get back: Type type = new TypeToken<ArrayList<Integer>>(){}.getType()
      8. ArrayList<Integer> inList = gson.fromJson(json, type)
      9. for (int i : inList) { System.out.println(i)
      10. }}

      Positive Reactions
      1. JSON is a standard ([www.json.org]( URL_http://www.json.org)) .
      2. Actually to keep the example as simple as possible you could just use a string i.e.
      Negative Reactions
      1. That somebody who has 17.2k rep does not understand something so fundamental is truly worrying.
      2. If GSON does not work with correct JSON, then it is a bug.
      Other Reactions
      1. String json "[ 1, 2, 3 ]";.
      2. No - that would presuppose what json is created by gson.
      3. This code will work even if gson changes its implementaiton.

    10. JSON/GSON with changing keys into Java

      The following update generates a list of currencies from the currency data in the deserialized map. . details

      Reactions - Positive 5, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.annotations.SerializedName
      3. import com.google.gson.reflect.TypeToken
      4. import java.io.FileReader
      5. import java.lang.reflect.Type
      6. import java.math.BigDecimal
      7. import java.util.ArrayList
      8. import java.util.List
      9. import java.util.Map
      10. import java.util.Map.Entry
      11. public class Foo {
      12. public static void main(String[] args) throws Exception {
      13. Gson gson = new Gson()
      14. Type currencyDataMapType = new TypeToken<Map<String, CurrencyData>>() {}.getType()
      15. Map<String, CurrencyData> currencyDataMap =
      16. gson.fromJson(new FileReader("input.json"), currencyDataMapType)
      17. List<Currency> currencies = fromDataMap(currencyDataMap)
      18. System.out.println(currencies)
      19. }
      20. static List<Currency> fromDataMap(Map<String, CurrencyData> currencyDataMap) {
      21. List<Currency> currencies = new ArrayList<Currency>(currencyDataMap.size())
      22. for (Entry<String, CurrencyData> entry : currencyDataMap.entrySet()) {
      23. String code = entry.getKey()
      24. currencies.add(new Currency(code, currencyDataMap.get(code)))
      25. }
      26. return currencies
      27. }
      28. }
      29. class Currency {
      30. String code
      31. CurrencyData data
      32. Currency(String code, CurrencyData data) {
      33. this.code = code
      34. this.data = data
      35. }
      36. @Override
      37. public String toString() {
      38. return String.format("{code:%s, 7d:%s, 30d:%s, 24h:%s}", code, data._7d, data._30d, data._24h)
      39. }
      40. }
      41. class CurrencyData {
      42. @SerializedName("7d")
      43. BigDecimal _7d
      44. @SerializedName("30d")
      45. BigDecimal _30d
      46. @SerializedName("24h")
      47. BigDecimal _24h
      48. }

      Positive Reactions
      1. I know my fair share about Java, but have only used ArrayLists and the like.
      2. "is there a way to include the currency code like USD in the object?"
      3. This is much better, but is there a way to include the currency code like USD in the object?
      4. I was trying to do something like this, but couldn't get it to work.
      5. My android app is pretty much complete, except for the part where when I try to actually download that json from the internet, I get a stub error.
      Negative Reactions
      1. -- Yes, but it would require custom deserialization processing, which is not terribly involved, but since the JSON structure is such a poor fit for the target Java data structure, it's a little easier to just transform the Java objects into what you want after performing the simple deserialization steps demonstrated above.
      Other Reactions
      1. I've never used maps before."
      2. I've never used maps before.
      3. "How do you access the data once it's in that map?
      4. I've taken my school's AP Comp Sci course, but we only learned the minimum to take the AP test.
      5. -- I suggest learning the basics first.
      6. I'll post example code for doing so, which will include getting data out of the Map.
      7. How do you access the data once it's in that map?
      8. I've been told it's because I'm using the emulator, and actually need a device, which I don't have.
      9. There are plenty of online resources to learn how to program in Java.
      10. I found a work around before you posted this.

    11. Google Gson - deserialize list<class> object? (generic type)

      Since your raw type is array list you should try array list. Method to deserialize generic collection . details

      Reactions - Positive 2, Negative 1, Others 0

      1. Type listType = new TypeToken<ArrayList<YourClass>>() { }.getType()
      2. List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType)

      Positive Reactions
      1. excellent, thank you!
      2. Using actual version of GSON (2.2.4) it works again.
      Negative Reactions
      1. In new versions of GSON the TypeToken contructor is not public, hence here you get constructor not visible error.
      Other Reactions
      1. You can access the constructor here.
      2. What do you have to do in this case?
      3. :).

  35. Convert a JSON string to object in Java?

    None .. details

    1. Object obj = JsonReader.jsonToJava("[\"Hello, World\"]")

    • See Also (2)
    1. How to deserialize only some fields in JSON?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Reader reader = /* create reader from source */Streams.parse(new JsonReader(reader)).getAsJsonObject().get("wantedValue").getAsString()

    2. A better Java JSON library?

      I liked J2J---Json2Java from Sourceforge. Really easy to map JSON to almost any java object by only annotating the class using JsonElement and then passing the java and class to JsonReader like . details

      Reactions - Positive 0, Negative 0, Others 0

      1. MyClass myclass = (MyClass) new JsonReader(MyClass.class, jsonString).toObject()

  36. GSON desirialization of sometimes string and sometimes object

    None .. details

    1. String json ="{\"id\": 1, \"blob\": \"example text\"}"
    2. //String json = "{\"id\": 2, \"blob\": {\"to\": 1234, \"from\": 4321, \"name\": \"My_Name\"}}"
    3. Gson gson = new Gson()
    4. JsonElement element = gson.fromJson (json, JsonElement.class)
    5. JsonObject jsonObj = element.getAsJsonObject()
    6. JsonElement id = jsonObj.get("id")
    7. System.out.println(id)
    8. if(jsonObj.get("blob") instanceof JsonPrimitive ){ JsonElement blob = jsonObj.get("blob")
    9. System.out.println(blob)
    10. }else{ FromToName blob = gson.fromJson (jsonObj.get("blob"), FromToName.class)
    11. System.out.println(blob)
    12. }

  37. Gson - two json keys for a one field

    But you may use getter/setter if you like. This is the calling code and this is the result Box width=4 height=5 depth=1 Box width=4 height=5 depth=1 . .. details

    1. package stackoverflow.questions.q19332412
    2. import com.google.gson.*
    3. public class Q19332412 {
    4. /** * @param args */
    5. public static void main(String[] args) {
    6. String j1 = "{\"width\":4, \"height\":5, \"depth\"=1}"
    7. String j2 = "{\"w\":4, \"h\":5, \"d\"=1}"
    8. GsonBuilder gb = new GsonBuilder().registerTypeAdapter(Box.class, new BoxAdapter())
    9. Gson g = gb.create()
    10. System.out.println(g.fromJson(j1, Box.class))
    11. System.out.println(g.fromJson(j2, Box.class))
    12. }
    13. }

    • See Also (30)
    1. String Parse, JSON Stringify & GSON Parse of Date Fails

      Now in Java I attempt to parse it into a Java Object like so But I get this exception . You need to quote the Z too The SimpleDateFormat used in the GsonBuilder takes the unquoted Z to mean a time zone which your date string doesn't have. details

      Reactions - Positive 2, Negative 0, Others 0

      1. Gson gson = new GsonBuilder().setDateFormat(yyyy-MM-dd'T'HH:mm:ss.SSS'Z').create()

      Positive Reactions
      1. @Guido You're welcome!.
      2. Many thanks.
      Other Reactions
      1. Will mark as answered.

    2. Retrofit GSON serialize Date from json string into java.util.date

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package stackoverflow.questions.q18473011
      2. import com.google.gson.*
      3. public class Question {
      4. /** * @param args */
      5. public static void main(String[] args) {
      6. String s = "{ \"date\": \"2013-07-16\", \"created_at\": \"2013-07-16T22:52:36Z\"}"
      7. GsonBuilder builder = new GsonBuilder()
      8. builder.registerTypeAdapter(Foo.class, new FooDeserializer())
      9. Gson gson = builder.create()
      10. Foo myObject = gson.fromJson(s, Foo.class)
      11. System.out.println("Result: " + myObject)
      12. }
      13. }

    3. JSON pretty-print without changing the order

      If you want to keep the order you can use java.util.LinkedHashMap instead of org.json.simple.JSONObject. Simple example . details

      Reactions - Positive 2, Negative 7, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.GsonBuilder
      3. import java.util.LinkedHashMap
      4. import java.util.Map
      5. public class GsonProgram {
      6. public static void main(String[] args) throws Exception {
      7. Map<String, Integer> myJSon = new LinkedHashMap<String, Integer>()
      8. myJSon.put("zzz", 1)
      9. myJSon.put("aaa", 1)
      10. Gson gson = new GsonBuilder().setPrettyPrinting().create()
      11. System.out.println(gson.toJson(myJSon))
      12. }
      13. }

      Positive Reactions
      1. My source code has nothing fancy.
      2. Do you mean it is not a best practice or do you mean it is not going work at all?
      Negative Reactions
      1. You have to change JSONObjects into LinkedHashMap in your source code.
      2. I'm having problems to download and edit the source codes of simple-json using Maven.
      3. How many instances of JSONObjects you have in your source code?Replacing is really easy because LinkedHashMap has "put" method too.
      4. If you want to change library - OK, it will be working, but is really problematic.
      5. Why you do not want to change your source code?
      6. Can you show to us your real source code?
      7. I can't believe that you have so many JSONObjects that easier will be change library than your source code.
      Other Reactions
      1. Why do you want to change the library?
      2. This is not a solution.
      3. What you mean by saying 'This is not a solution.'
      4. It is why I was considering to change the library.
      5. Any further reading?
      6. Only many JJSONArrays and SONObjects inside other JSONObjects.
      7. I thought changing HashMap to LinkedHashMap in the original implementation of simple-json would solve the issue.
      8. So you have to change only the type of object.

    4. gson.toJson() throws StackOverflowError

      To fix it you could use TypeAdapter for your object. For example if you need only generate String from your object you could use adapter like this and register it like this or like this if you have interface and want to use adapter for all its subclasses . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new GsonBuilder() .registerTypeAdapter(BomItem.class, new MyTypeAdapter<BomItem>()) .create()

    5. gson.toJson() throws StackOverflowError

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new GsonBuilder() .registerTypeHierarchyAdapter(BomItemInterface.class, new MyTypeAdapter<BomItemInterface>()) .create()

    6. How do you get GSON to omit null or empty objects and empty arrays and lists?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Collection.class, new CollectionAdapter()).create()

    7. can't Deserialize a list of different types of children objects

      I've just written an article about it on my blog javajson-mapping-with-gson And here is the section you're interested in javajson-mapping-with-gson/#Preserving_type_information gson/#Preserving_type_information Please ask if you still have the issue. EDIT here is a full sample for your specific situation . details

      Reactions - Positive 2, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.GsonBuilder
      3. import com.google.gson.typeadapters.RuntimeTypeAdapterFactory
      4. public class Program{ public static class Packet { public Message[] DATA
      5. } public static enum MessageType { WHOAREYOU, TimeData, Ready, LocationData } //my parent message class: public static class Message { public MessageType getMessageType() { return MESSAGE_TYPE
      6. } public void setMessageType(MessageType MessageType) { this.MESSAGE_TYPE = MessageType
      7. } private MessageType MESSAGE_TYPE
      8. //declaring public for simplicity public String SENDER
      9. public String SENDER_TYPE
      10. } //sample child class: public static class TimeMessage extends Message { private int tick
      11. public int getTick() { return tick
      12. } public TimeMessage(int tick) { this.tick = tick
      13. } } public static void main(String[] args) { Message[] messages = { new TimeMessage(123) }
      14. GsonBuilder builder = new GsonBuilder()
      15. builder.registerTypeAdapterFactory(RuntimeTypeAdapterFactory.of(Message.class, "$type").registerSubtype(TimeMessage.class))
      16. Gson gson = builder.create()
      17. String json = gson.toJson(messages)
      18. Message[] outMessages = gson.fromJson(json, Message[].class)
      19. TimeMessage tm = (TimeMessage)outMessages[0]
      20. }}

      Positive Reactions
      1. +1 Thank you!
      2. Can you please repost the relevant sections from your blog here so that in case your blog goes down, your answer is still useful in the future?
      Other Reactions
      1. ).
      2. @Kevin: I've updated the answer with some relevant code.
      3. :).

    8. How to create GSON custom serializer that writes raw string?

      If you don't need it just return null in the method body. This is how you use it Cheers. details

      Reactions - Positive 1, Negative 2, Others 0

      1. GsonBuilder builder = new GsonBuilder()
      2. builder.registerTypeAdapter(MyPayload.class, new MyTypeAdapter())
      3. Gson gson = builder.create()
      4. String jsonString = gson.toJson(somethingThatContainsMyPayloads)

      Positive Reactions
      1. Well, I made a test with return "AB\\..{_}[]\"C"; in getAsJson() and this is the String being generated: "AB\\..{_}[]\"C"; so no escaping.
      Negative Reactions
      1. Thanks for the answer, but I am afraid the writer.value(String) method will actually escape the string...
      2. I'm afraid it's even no longer useful, though in fact very unescaped :).

    9. How to do Custom Serialization using GSON?

      First of all you can't get output as "student":{"name":"sam","rollNumer":1 student":{"name":"tom","rollNumer":2 because you are trying to convert object into json not array of object. I tried your code and I am getting following output "students":[{"name":"sam","rollNumber":1},{"name":"tom","rollNumber":2}] Here is code . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Student[] students = new Student[2]
      2. students[0] = new Student("sam", 1)
      3. students[1] = new Student("tom", 2)
      4. School school = new School(students)
      5. Gson gson = new GsonBuilder().disableHtmlEscaping().create()
      6. System.out.println(gson.toJson(school))

      Other Reactions
      1. School has array of Student objects.

    10. Gson Expected BEGIN_ARRAY but was STRING at line 1 column 62

      With the above defined class your program should work just fine. Produces If you find yourself needing to retain the current CFS structure though you would need to manually parse the JSON into it. details

      Reactions - Positive 1, Negative 0, Others 0

      1. final Gson gson = new GsonBuilder().create()
      2. final CFS results = gson.fromJson(json, CFS.class)
      3. Assert.assertNotNull(results)
      4. Assert.assertNotNull(results.getFiles())
      5. System.out.println(results.getFiles())

      Positive Reactions
      1. Thanks, it all works now.
      Other Reactions
      1. :).

    11. Json to Object using Gson

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. GsonBuilder builder = new GsonBuilder()
      2. Gson gson = builder.enableComplexMapKeySerialization().create()
      3. Collection<DocumentBO> obj = gson.fromJson(str, type)

    12. parse a JSON feed using GSON and get an array instead of multi params

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new GsonBuilder() .registerTypeAdapter(MyResponse.class, new MyDeserializer()) .create()

    13. Play Framework renderJSON gives InvocationTargetException

      Using the information found here Exclusion-Strategies User-Defined-Exclusion-Strategies i've come up with the following solution. Using the Expose annotation to mute one side of the bi-directional relationship at render time definitely solved the issue. details

      Reactions - Positive 1, Negative 0, Others 0

      1. /***************** Models ****************/class Person { @Expose public int age
      2. @Expose public String name
      3. @Expose @OneToMany(mappedBy="owner") public Dog dog
      4. //Constructors and other code}class Dog { @Expose public String name
      5. @ManyToOne(fetch=FetchType.Eager) public Person owner
      6. //Constructor and other code}/**************Controller********************/public class Application extends Controller { public static Gson gson = GsonBuilder.excludeFieldsWithoutExposeAnnotation().create
      7. public static void allPersons() { List<Person> people = Person.findAll()
      8. renderJSON(gson.toJson(people))
      9. //Error should be taken care of }}

      Positive Reactions
      1. Yep I've been much happier with FlexJSON than GSON in Play too.

    14. JSON to java object using gson

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new GsonBuilder() .excludeFieldsWithModifier() .create()

    15. JSON array in GSON parses, but objects are empty

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public static void main(String[] args) throws Exception{ String jsonOutput = "[{\"answer\":{\"text\":\"text1\"}},{\"answer\":{\"text\":\"text2\"}} ]"
      2. GsonBuilder gsonBuilder = new GsonBuilder()
      3. gsonBuilder.registerTypeAdapter(Answer.class, new AnswerDeserializer())
      4. Gson gson = gsonBuilder.create()
      5. Answer[] a = gson.fromJson(jsonOutput, Answer[].class)
      6. for(Answer i:a) { System.out.println(i.text)
      7. } }

    16. What is the most suitable Java data structure for representing JSON?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String jsonString
      2. // initialized as you canGsonBuilder gsonBuilder = new GsonBuilder()
      3. gsonBuilder.setDateFormat("MM-dd-yyyy HH:mm")
      4. // setting custom date formatGson gson = gsonBuilder.create()
      5. Product product = gson.fromJson(jsonString, Product.class)
      6. // Do whatever you want with the object it has its fields loaded from the json

    17. What is the most suitable Java data structure for representing JSON?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. GsonBuilder gsonBuilder = new GsonBuilder()
      2. gsonBuilder.setDateFormat("MM-dd-yyyy HH:mm")
      3. // setting custom date formatGson gson = gsonBuilder.create()
      4. String jsonString = gson.toJson(product)

    18. Custom Conversion from Java Object to JSON Object

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import static org.junit.Assert.*
      2. import com.google.gson.*
      3. import org.junit.Test
      4. public class JSONTest {
      5. @Test
      6. public final void testSerializeWithDTRowId() {
      7. Entity entity = new Entity()
      8. entity.creationTime = 0
      9. entity.enabled = true
      10. entity.id = 1
      11. entity.loginDuration = 0
      12. entity.online = false
      13. entity.userName = "someone"
      14. GsonBuilder builder = new GsonBuilder()
      15. builder.registerTypeAdapter(Entity.class, new EntityJsonSerializer())
      16. Gson gson = builder.create()
      17. String json = gson.toJson(entity)
      18. String expectedJson =
      19. "{\"creationTime\":0,\"enabled\":true,\"id\":1,\"loginDuration\":0,\"online\":false,\"userName\":\"someone\",\"DT_RowId\":1}"
      20. assertEquals(expectedJson, json)
      21. }
      22. }

    19. Converting json string of Intent to object of Intent giving exception

      My bet is Intent#uriString is of type android.net.Uri which has no no-arg public constructor. I means you have to write JsonDeserializer<Uri like this and then register it via GsonBuilder EDIT You have to register custom adapters in case any property doesn't define public no-arg constructor. details

      Reactions - Positive 4, Negative 2, Others 0

      1. Gson gson = new GsonBuilder() .registerTypeAdapter(Uri.class, new UriDeserializer()) .create()

      Positive Reactions
      1. Thanks a lot.
      2. I think its working but let me check completely then I'll accept it :).
      3. Can you please elaborate it why we are doing this?
      4. But it's omitting lot of data after again conversion from object to json string I am getting something like:{"targetIntent":{ "mAction":"android.intent.action.VIEW", "mData":{ }, "mFlags":0 }}.
      Negative Reactions
      1. Isn't?And if I am using src.getAsString() it gives exception like:08-31 02:25:22.274: W/System.err(2946): java.lang.UnsupportedOperationException: JsonObjectI change src.getAsString() to src.toString().
      2. ...plus - since comments are getting too long and you resolved your original problem from question - I suggest to finish EOT here and ask new question if you have another problem.
      Other Reactions
      1. "from object to json string" is the other way (gson.toJson(Intent)) - you asked about gson.fromJson(String) here, that's not the same issue.
      2. UriDeserializer deserializes, while you're trying to serialize Intent object to JSON, to you should register JsonSerializer also, which will return new JsonPrimitive(src.toString());.
      3. Finally solved :).
      4. yes but if I convert again object to json using gson.toJson then it should give the same strig.

    20. Create and read tree data structure from json string dynamically

      This is what i tried. Year:another values OR Report:some valeus AND Citation:some valeues AND Field another should be something like if The MYOperator enum is and AtomicOperation Is Then You can Build the necessary AtomicOperation Object using the below code Below is the complete ConvertJsonToObject class . details

      Reactions - Positive 4, Negative 1, Others 0

      1. public class ConvertJsonToObject {
      2. private static Gson gson = new GsonBuilder().create()
      3. public static final <T> T getFromJSON(String json, Class<T> clazz) {
      4. return gson.fromJson(json, clazz)
      5. }
      6. public static final <T> String toJSON(T clazz) {
      7. return gson.toJson(clazz)
      8. }
      9. }

      Positive Reactions
      1. hey try now...i have written proper toString() method for AtomicOperation.
      2. hey i have edited the code...copy the entire edited code with updated toString method then finally call _r.toString() and you will get ((((Field : Value) AND (Citation : Citation)) AND (Report : Report1)) OR (Year : 2001)) as output.
      3. At the end produce same output!!
      4. _r gives a hash code!.
      Negative Reactions
      1. with that what I'm getting is "({lhs={lhs={lhs=Field, rhs=Value, operator=EQUAL_TO}, rhs={lhs=Citation, rhs=Citation, operator=EQUAL_TO}, operator=AND}, rhs={lhs=Report, rhs=Report1, operator=EQUAL_TO}, operator=AND} OR {lhs=Year, rhs=2001, operator=EQUAL_TO})"I think it's because AtomicOperation to string get executed only one time.
      Other Reactions
      1. ?
      2. also modify toString method of EQUAL_TO in the enum MyOperator.
      3. The enum should be in the main class right ?
      4. let us [continue this discussion in chat]( URL_http://chat.stackoverflow.com/rooms/14788/discussion-between-rj45-and - byter).
      5. where and how to get final outcome.
      6. ConvertJsonToObject.getFromJSON(json, AtomicOperation.class) gives "({lhs={lhs={lhs=Field, rhs=Value, operator=EQUAL_TO}, rhs={lhs=Citation, rhs=Citation, operator=EQUAL_TO}, operator=AND}, rhs={lhs=Report, rhs=Report1, operator=EQUAL_TO}, operator=AND} OR {lhs=Year, rhs=2001, operator=EQUAL_TO})" and it never execute "if (operation.getLhs().getClass().equals(LinkedHashMap.class)) " part.

    21. Create and read tree data structure from json string dynamically

      let us continue this discussion in chat byter). . details

      Reactions - Positive 1, Negative 0, Others 0

      1. Use Something like Google Gsonclass ConvertJsonToObject { private static Gson gson = new GsonBuilder().create()
      2. public static final <T> T getFromJSON(String json, Class<T> clazz) { return gson.fromJson(json, clazz)
      3. }}String jsonString = "{"category":"Case Law","query":{"AND":{"Year the case was instituted":{"having":"","exact":"","any":"","none":""},"AND":{"Report":{"having":"","exact":"","any":"","none":""},"Citation":{"having":"","exact":"","any":"","none":""}}}}}"Now you can use ConvertJsonToObject.getFromJSON(jsonString,Map.class)

      Positive Reactions
      1. But how to create some thing like (Year:another values OR (Report:some valeus AND Citation:some valeues)).

    22. How to properly convert List of specific objects to Gson?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public String messagesToJson(List<Message> messages) { GsonBuilder gsonBuilder = new GsonBuilder()
      2. Gson gson = gsonBuilder.registerTypeAdapter(Message.class, new MessageAdapter()).create()
      3. return gson.toJson(messages)
      4. }

    23. Map to JSON in Java

      What you want is pretty printing. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new GsonBuilder().setPrettyPrinting().create()
      2. String json = gson.toJson(yourMap)

      Other Reactions
      1. i want the children to be under ' "children": [ .. ] '.

    24. GSON: How to move fields to parent object

      You can probably do this by writing and then registering a Serialization-and-Deserialization custom-serializer for Step and making sure inside it you work with Duration etc instead of Data. The code for the custom serializer below I'm writing off the top of my head. details

      Reactions - Positive 4, Negative 1, Others 0

      1. // registering your custom serializer:GsonBuilder builder = new GsonBuilder ()
      2. builder.registerTypeAdapter (Step.class, new StepSerializer ())
      3. Gson gson = builder.create ()
      4. // now use 'gson' to do all the work

      Positive Reactions
      1. I haven't tested a single line of code I wrote, although the hope is that it is fairly correct.
      2. Good luck.
      3. I highly recommend the rest of the API documentation for JsonObject as well.
      4. Thanks.
      Negative Reactions
      1. I've never done weird stuff like this before.
      Other Reactions
      1. googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonObject.html#re move(java.lang.String)).
      2. I'm not too sure because everything I've written is based on Gson documentation.
      3. Is there a way to create the step variable from the src Step and just remove it's data object?
      4. I've updated my question with additional fields inside the data-object.
      5. @DennisMadsen - There is a way to do that using [remove]( URL_http://google-gson .
      6. If that's possible I wouldn't have to add the start and end name again.
      7. I only need to serialize, so deserialize is not important.
      8. Yes, I did.
      9. This really depends.
      10. It almost worked except from the fact, that I've created a LocationAdapterFactory which modify all the locations in my JSON tree, but when I manually add a location, it seems that this isn't changed by my LocationAdapterFactory.
      11. The above was just an example of my structure.
      12. @DennisMadsen - I've updated my answer to reflect your change.
      13. Any clue how I can do that?
      14. Caveat: My answer is based on Gson documentation.
      15. Show an example with two additional fields and I'll see what I can think of.
      16. @DennisMadsen - Did you actually implement the serializer and see that it works for you, before marking this answer correct?
      17. In fact my data-object contains additional fields, which needs to be included in the toJsonTree.

    25. GSON not calling my TypeAdapter for a type which is an interface

      In your test where is Gson builder with adapter. You should change it . details

      Reactions - Positive 1, Negative 1, Others 0

      1. public void testJson() throws Exception{ Player player = new MagicPlayer()
      2. //BeanUtils.createDefault(Player.class)
      3. player.setName("Alice")
      4. // this is wrong if you want adapter /* Gson gson = new Gson()
      5. */ // this is what you nead Gson gson = new GsonBuilder() .registerTypeAdapter(Player.class, new PlayerTypeAdapter()) .create()
      6. System.out.println(gson.toJson(bean))
      7. }

      Positive Reactions
      1. Please read the question before updating your answer any further.
      Negative Reactions
      1. I put a breakpoint on the line where I am throwing the exception, but the line is never reached.
      Other Reactions
      1. ).
      2. Okay, updated to remove CGLIB from the equation.
      3. Gson still doesn't call my type adapter at any point.
      4. Ergo, Gson is not calling my serialiser.
      5. You can see in the question above how PlayerTypeAdapter is implemented.
      6. Either that, or Gson doesn't call type adapters for interfaces (which just means I can't use it.
      7. There must be something else I'm supposed to do.

    26. JSON - deserialization of dynamic object using Gson

      He does not know what type the object is going to be before he performs the deserialization. this code should be i think(if you are parsing a json doc). details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new GsonBuilder.create()

      Other Reactions
      1. This would do nothing.
      2. Your suggestion is exactly equivalent to the original code.

    27. Polymorphism with gson

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class Test {public static void main(String[] args) { IAnimal animals[] = new IAnimal[]{new Cat("Kitty"), new Dog("Brutus", 5)}
      2. Gson gsonExt = null
      3. { GsonBuilder builder = new GsonBuilder()
      4. builder.registerTypeAdapter(IAnimal.class , new IAnimalAdapter())
      5. gsonExt = builder.create()
      6. } for (IAnimal animal : animals) { String animalJson = gsonExt.toJson(animal, IAnimal.class)
      7. System.out.println("serialized with the custom serializer:" +animalJson)
      8. IAnimal animal2 = gsonExt.fromJson(animalJson, IAnimal.class)
      9. System.out.println(animal2.sound())
      10. }}

    28. How to keep fields sequence in Gson serialization

      E.g. and use it as follows This maintains the order as you've specified in the serializer. details

      Reactions - Positive 6, Negative 2, Others 0

      1. Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, new FooJsonSerializer()).create()
      2. String json = gson.toJson(foo)
      3. // ...

      Positive Reactions
      1. Maybe you're doing something for which there is an easier way to do it.
      2. I'd prefer using a custom deserializer over using the JsonWriter directly in almost every situation.
      3. I'd rather prefer JsonWriter recomended by @Programmer Bruce.
      4. For the specific problem you described, I'd take BalusC's solution a few steps further, to make it more generic and to make the element order externally configurable.
      5. thanks.
      6. (For the interested: The underlying implementation that provides for this feature stores added elements using a LinkedHashMap.
      Negative Reactions
      1. That this approach works is unfortunately not in the documentation for the JsonObject.add(String, JsonElement) method (or in the documentation for the addProperty methods), rather it's revealed in the documentation for the entrySet() method!
      2. And yes, shame on .NET json parser.
      Other Reactions
      1. ).
      2. It could then be reused for different objects.
      3. @romanovsky Too heavy?
      4. However in my case the solution becomes too heavy.

    29. gson ignoring map entries with value=null

      Thank you . TOC-Null-Object-Support RTFM . details

      Reactions - Positive 1, Negative 0, Others 0

      1. Gson gson = new GsonBuilder().serializeNulls().create()

      Positive Reactions
      1. So I think you can accept then answer ... or you prefer I remove the 'RTFM' before ;-).
      Other Reactions
      1. OK, I deserved that... :p.

    30. Deserializing an abstract class in Gson

      Thanks. I'd suggest adding a custom on/docs/javadocs/com/google/gson/JsonDeserializer.html JsonDeserializer for Nodes You will be able to access the JsonElement representing the node in the deserializer's method convert that to a JsonObject and retrieve the field that specifies the type. details

      Reactions - Positive 4, Negative 0, Others 0

      1. Gson gson = new GsonBuilder() .registerTypeAdapter(Node.class, new NodeDeserializer()) .create()

      Positive Reactions
      1. Thanks!.
      2. That worked perfectly.
      3. I'd upvote you, but my reputation isn't high enough :(.
      4. @eng-carlin It's customary to upvote and accept an answer if it works for you, so if you could do that I'd appreciate it.
      Other Reactions
      1. The green check mark has been clicked.

  38. Gson - two json keys for a one field

    trapo yes indeed . One solution could be to write a TypeAdapter like this Pay attention that put Box and BoxAdapter into the same package. .. details

    1. package stackoverflow.questions.q19332412
    2. import com.google.gson.TypeAdapter
    3. import com.google.gson.stream.*
    4. import java.io.IOException
    5. public class BoxAdapter extends TypeAdapter<Box> {
    6. @Override
    7. public void write(JsonWriter out, Box box) throws IOException {
    8. out.beginObject()
    9. out.name("w")
    10. out.value(box.width)
    11. out.name("d")
    12. out.value(box.depth)
    13. out.name("h")
    14. out.value(box.height)
    15. out.endObject()
    16. }
    17. @Override
    18. public Box read(JsonReader in) throws IOException {
    19. if (in.peek() == JsonToken.NULL) {
    20. in.nextNull()
    21. return null
    22. }
    23. in.beginObject()
    24. Box box = new Box()
    25. while (in.peek() == JsonToken.NAME) {
    26. String str = in.nextName()
    27. fillField(in, box, str)
    28. }
    29. in.endObject()
    30. return box
    31. }
    32. private void fillField(JsonReader in, Box box, String str) throws IOException {
    33. switch (str) {
    34. case "w":
    35. case "width":
    36. box.width = in.nextInt()
    37. break
    38. case "h":
    39. case "height":
    40. box.height = in.nextInt()
    41. break
    42. case "d":
    43. case "depth":
    44. box.depth = in.nextInt()
    45. break
    46. }
    47. }
    48. }

  39. How to split a String result from a JSON URL to individual java objects

    None .. details

    1. package stackoverflow.questions
    2. import com.google.gson.Gson
    3. import java.util.List
    4. public class Question {
    5. class Record {
    6. Long timestamp
    7. String deviceId
    8. Long temperature
    9. }
    10. class Container {
    11. List<Record> records
    12. }
    13. public static void main(String[] args) {
    14. String json =
    15. "{ \"status\": \"success\", \"records\": [{\"timestamp\": 1381222871868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222901868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222931868,\"deviceId\": \"288\",\"temperature\": 17 } ]} "
    16. Gson g = new Gson()
    17. Container c = g.fromJson(json, Container.class)
    18. for (Record r : c.records) System.out.println(r)
    19. }
    20. }

    • See Also (1)
    1. How to gather data from a JSON URL and display it

      here's how to do it via Google-Gson . An high-level Gson parsing answer Of course this is the result 1381222871868 1381222901868 1381222931868 . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package stackoverflow.questions.q19252374
      2. import com.google.gson.Gson
      3. import java.util.List
      4. public class Q19252374 {
      5. class Record {
      6. Long timestamp
      7. String deviceId
      8. Long temperature
      9. }
      10. class Container {
      11. List<Record> records
      12. }
      13. public static void main(String[] args) {
      14. String json =
      15. "{ \"status\": \"success\", \"records\": [{\"timestamp\": 1381222871868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222901868,\"deviceId\": \"288\",\"temperature\": 17 },{\"timestamp\": 1381222931868,\"deviceId\": \"288\",\"temperature\": 17 } ]} "
      16. Gson g = new Gson()
      17. Container c = g.fromJson(json, Container.class)
      18. for (Record r : c.records) System.out.println(r.timestamp)
      19. }
      20. }

  40. How to gather data from a JSON URL and display it

    If you could alter this for gson then it'll be good for your requirement. here's how to do it via Google-Gson . .. details

    1. class MyRecord{private long timestamp
    2. private String deviceId
    3. private Integer temperature
    4. //Getters & setters}public static void main(String... args){ String myJsonString=callUrl("http://mydomain.com/x.json")
    5. JsonParser jp = new JsonParser()
    6. JsonElement ele = jp.parse(myJsonString)
    7. Gson gg = new Gson()
    8. Type type = new TypeToken<List<MyRecord>>() { }.getType()
    9. List<MyRecord> lst= gg.fromJson(ele.getAsJsonObject().get("records"), type)
    10. //Now the json is parsed in a List of MyRecord, do whatever you want to with it}

  41. Gson deserialize complex object with recursive dependencies

    Just had to use the function fromJson instead of toJson with the same GraphAdapterBuilder structure. Output is . .. details

    1. ... GsonBuilder gsonBuilder = new GsonBuilder()
    2. new GraphAdapterBuilder() .addType(ClassA.class) .addType(ClassB.class) .registerOn(gsonBuilder)
    3. gson = gsonBuilder.create()
    4. lassB B = gson.fromJson(json,ClassB.class)
    5. System.out.println("B " + B.vector)
    6. for(ClassA classA:B.vector){ System.out.println(classA.field + " " + classA.parent)
    7. }

  42. Gson Generics attribute

    None .. details

    1. public class LoadJson<T> {
    2. Response<T> load(String responseElement, Type classType) {
    3. Gson gson = new Gson()
    4. Response<T> response = gson.fromJson(responseElement, classType)
    5. return response
    6. }
    7. }

    • See Also (13)
    1. Composing a simple JSON response in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. public class Main {
      3. public static void main(String[] args) {
      4. MyObj obj = new MyObj("PEBKAC", false)
      5. Gson gson = new Gson()
      6. System.out.println(gson.toJson(obj))
      7. }
      8. }

    2. How do I parse this JSON string using GSON in servlet

      When I am unable to solve something I write the smallest possible program to verify my understanding is correct. In your case I came up with this Compiled and ran and it outputs So I still believe that the input that the servlet receives is not correct or you have not provided an accurate description of your existing code). details

      Reactions - Positive 3, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. import java.util.List
      3. public class GsonTest {
      4. public static class Data {
      5. private List<String> title
      6. public List<String> getTitle() {
      7. return title
      8. }
      9. public Data() {}
      10. }
      11. public static void main(String[] args) {
      12. Gson gson = new Gson()
      13. Data data = gson.fromJson("{\"title\":[\"1\",\"2\"]}", Data.class)
      14. System.out.println(data.getTitle())
      15. }
      16. }

      Positive Reactions
      1. this example really helped me, as I was working on json first time, I was looking for complete general solution, searched on SO but those questions were specific to their issues, anyways thanks +1 and and aceepting this.
      2. Yes this example works, thanks for this I will try to make my code by comparing it with this.
      3. thanks.

    3. Custom Conversion from Java Object to JSON Object

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.*
      2. import java.lang.reflect.Type
      3. public class EntityJsonSerializer implements JsonSerializer<Entity> {
      4. @Override
      5. public JsonElement serialize(Entity entity, Type typeOfSrc, JsonSerializationContext context) {
      6. entity.DT_RowId = entity.id
      7. Gson gson = new Gson()
      8. return gson.toJsonTree(entity)
      9. }
      10. }

    4. Converting Map<String,String> into json

      Have a look at example 1.4 on this page simple/wiki/EncodingExamples#Example_1-4_-_Encode_a_JSON_object Using_Map_and_streaming simple/wiki/EncodingExamples#Example_1-4_-_Encode_a_JSON_object Using_Map_and_streaming . You can also try something like this with Gson Library The output look like this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.stackoverflow.works
      2. import com.google.gson.Gson
      3. import com.google.gson.reflect.TypeToken
      4. import java.lang.reflect.Type
      5. import java.util.HashMap
      6. import java.util.Map
      7. /* * @Author: sarath_sivan */ public class MapToJsonConverter {
      8. /* * @Description: Method to convert Map to JSON String * @param: map Map<String, String> * @return: json String */
      9. public static String convert(Map<String, String> map) {
      10. Gson gson = new Gson()
      11. String json = gson.toJson(map)
      12. return json
      13. } /* * @Description: Method to convert JSON String to Map * @param: json String * @return: map Map<String, String> */
      14. public static Map<String, String> revert(String json) {
      15. Gson gson = new Gson()
      16. Type type = new TypeToken<Map<String, String>>() {}.getType()
      17. Map<String, String> map = gson.fromJson(json, type)
      18. return map
      19. } /* * @Description: Method to print elements in the Map * @param: map Map<String, String> * @return: void */
      20. public static void printMap(Map<String, String> map) {
      21. for (String key : map.keySet()) {
      22. System.out.println("map.get(\"" + key + "\") = " + map.get(key))
      23. }
      24. } /* * @Description: Method to print the JSON String * @param: json String * @return: void */
      25. public static void printJson(String json) {
      26. System.out.println("json = " + json)
      27. } /* * @Description: Main method to test the JSON-MAP convert/revert logic */
      28. public static void main(String[] args) {
      29. Map<String, String> paymentCards = new HashMap<String, String>()
      30. paymentCards.put("card_switch", "Master")
      31. paymentCards.put("issuing_bank", "ICCI")
      32. paymentCards.put("card_Type", "DebitCard")
      33. String json = convert(paymentCards)
      34. //converting Map to JSON String System.out.println("Map to JSON String")
      35. System.out.println("******************")
      36. printJson(json)
      37. System.out.println()
      38. paymentCards = revert(json)
      39. //converting JSON String to Map System.out.println("JSON String to Map")
      40. System.out.println("******************")
      41. printMap(paymentCards)
      42. }
      43. }

    5. GSON/Jackson in Android

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. import java.io.FileReader
      3. public class GsonFoo {
      4. public static void main(String[] args) throws Exception {
      5. Gson gson = new Gson()
      6. Thing thing = gson.fromJson(new FileReader("input.json"), Thing.class)
      7. System.out.println(gson.toJson(thing))
      8. }
      9. }

    6. JSON/GSON with changing keys into Java

      With Gson here's what that solution would look like. The following update generates a list of currencies from the currency data in the deserialized map. details

      Reactions - Positive 5, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.annotations.SerializedName
      3. import com.google.gson.reflect.TypeToken
      4. import java.io.FileReader
      5. import java.lang.reflect.Type
      6. import java.math.BigDecimal
      7. import java.util.Map
      8. public class Foo {
      9. public static void main(String[] args) throws Exception {
      10. Gson gson = new Gson()
      11. Type currencyMapType = new TypeToken<Map<String, Currency>>() {}.getType()
      12. Map<String, Currency> currencyMap =
      13. gson.fromJson(new FileReader("input.json"), currencyMapType)
      14. System.out.println(currencyMap)
      15. }
      16. }
      17. class Currency {
      18. @SerializedName("7d")
      19. BigDecimal _7d
      20. @SerializedName("30d")
      21. BigDecimal _30d
      22. @SerializedName("24h")
      23. BigDecimal _24h
      24. @Override
      25. public String toString() {
      26. return String.format("{7d:%s, 30d:%s, 24h:%s}", _7d, _30d, _24h)
      27. }
      28. }

      Positive Reactions
      1. I know my fair share about Java, but have only used ArrayLists and the like.
      2. "is there a way to include the currency code like USD in the object?"
      3. This is much better, but is there a way to include the currency code like USD in the object?
      4. I was trying to do something like this, but couldn't get it to work.
      5. My android app is pretty much complete, except for the part where when I try to actually download that json from the internet, I get a stub error.
      Negative Reactions
      1. -- Yes, but it would require custom deserialization processing, which is not terribly involved, but since the JSON structure is such a poor fit for the target Java data structure, it's a little easier to just transform the Java objects into what you want after performing the simple deserialization steps demonstrated above.
      Other Reactions
      1. I've never used maps before."
      2. I've never used maps before.
      3. "How do you access the data once it's in that map?
      4. I've taken my school's AP Comp Sci course, but we only learned the minimum to take the AP test.
      5. -- I suggest learning the basics first.
      6. I'll post example code for doing so, which will include getting data out of the Map.
      7. How do you access the data once it's in that map?
      8. I've been told it's because I'm using the emulator, and actually need a device, which I don't have.
      9. There are plenty of online resources to learn how to program in Java.
      10. I found a work around before you posted this.

    7. Help me to parse this kind of json for android

      Here's what that would look like. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. public class Foo {
      2. public static void main(String[] args) throws Exception {
      3. Gson gson = new Gson()
      4. Type thingsType = new TypeToken<List<Vulume>>() {}.getType()
      5. List<Vulume> things = gson.fromJson(new FileReader("input.json"), thingsType)
      6. System.out.println(gson.toJson(things))
      7. }
      8. }
      9. class Vulume {
      10. String id
      11. String name
      12. String status
      13. List<Vulume> vulumes
      14. }

      Positive Reactions
      1. Thank you for your reply!
      2. An example of the above helped me, I'm right understand that i can get exact key: value from my class in json?

    8. Deserialization of generic collections with Gson

      Here is such a working example using the names and types from the original question. . details

      Reactions - Positive 6, Negative 2, Others 0

      1. import com.google.gson.Gson
      2. import java.io.FileReader
      3. public class Foo {
      4. public static void main(String[] args) throws Exception {
      5. Gson gson = new Gson()
      6. resultContainer result = gson.fromJson(new FileReader("input.json"), resultContainer.class)
      7. System.out.println(gson.toJson(result))
      8. }
      9. }
      10. class resultContainer {
      11. String fieldA
      12. MyCollectionContainer myCollection
      13. }
      14. class MyCollectionContainer {
      15. SomeOtherClass[] AnotherClass
      16. }
      17. class SomeOtherClass {
      18. String objectAfieldA
      19. String objectAfieldB
      20. }

      Positive Reactions
      1. Great answer, spot on!
      2. Maybe some folks think that if the JSON they generate is valid, that's good enough, even if it is not consistently structured.
      3. Thanks again for the answer and for the workaround.
      4. I ajusted my java structure and I'm happy again.
      5. Thanx, Bruce.
      6. The service I use may sometimes only carry one item inside the AnotherClass element in which case it is not encoded as a json array (casting perfectly to SomeOtherClass[]), but just a plain SomeOtherClass type - leaving the array brackets.
      Negative Reactions
      1. What you've described is an all-too-often occurring problem.
      2. Gson unfortunately does not yet have a simple configuration available to handle this often-occurring problem.
      Other Reactions
      1. Is this JSON standard, and do you guys have a workaround?
      2. I posted such an example in response to the question at URL_http://stackoverflow.com/questions/6223023 .
      3. Custom deserialization processing is necessary.
      4. Another issue came up now...
      5. That breaks my deserialization.
      6. If I add the brackets manually, it parses again.

    9. Parsing Gson with Json not working for Android

      The JSON structure is Here is such an example using the same JSON as in the original question. . details

      Reactions - Positive 3, Negative 3, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.reflect.TypeToken
      3. import java.io.FileReader
      4. import java.lang.reflect.Type
      5. import java.util.ArrayList
      6. public class Foo {
      7. public static void main(String[] args) throws Exception {
      8. Gson gson = new Gson()
      9. Type collectionType = new TypeToken<ArrayList<ArticleContainer>>() {}.getType()
      10. ArrayList<ArticleContainer> articles =
      11. gson.fromJson(new FileReader("input.json"), collectionType)
      12. System.out.println(gson.toJson(articles))
      13. }
      14. }
      15. class ArticleContainer {
      16. Article article
      17. }
      18. class Article {
      19. public int author_id
      20. public String body
      21. public String catagory
      22. public String created_at
      23. public int id
      24. public String published
      25. public String updated_at
      26. }

      Positive Reactions
      1. Thanks a million!.
      2. thanks for your reply :).
      3. I'm parsing something similar which explained in hour example... the problem i cant parse is: "classification":"ab 0","genres":"Drama","trailer": {"de": [{"id":"11471452", "name":"Trailer 1", "hq":false}],"ov":[]},"trailer_url":"xxx",... beginning with trailer.. its just one entry there, everything else works...
      Negative Reactions
      1. thanks a lot for your response... the format in comments is really bad :) so thanks for your advice, for now i have found a workaround.
      2. but i think i've found this problem a few times on the web, but wasnt able to understand the solution.
      3. I#m sorry, i dont understand how to use this....
      Other Reactions
      1. That was exactly the tweak I needed.
      2. @cV2 -- If you have a question, I suggest creating a new post.

    10. Deserialize JSON to Collection of Unknown Types

      Here's an example that demonstrates this point. input.json Contents Foo.java The output of this example is . details

      Reactions - Positive 2, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.reflect.TypeToken
      3. import java.io.FileReader
      4. import java.lang.reflect.Type
      5. import java.util.Map
      6. public class Foo {
      7. public static void main(String[] args) throws Exception {
      8. Gson gson = new Gson()
      9. Type mapOfStringObjectType = new TypeToken<Map<String, String>>() {}.getType()
      10. Map<String, String> map = gson.fromJson(new FileReader("input.json"), mapOfStringObjectType)
      11. System.out.println(map)
      12. }
      13. }

      Positive Reactions
      1. Gson issue 325 addresses simple deserialization to Map.
      2. Please don't hesitate to vote for its implementation at URL_http://code.google.com/p/google - gson/issues/detail?id=325.
      Negative Reactions
      1. Note that Jackson ( URL_http://jackson.codehaus.org ) can deserialize the example JSON above to a Map without custom processing, and JSON-lib ( URL_http://json - lib.sourceforge.net) can similarly deserialize to a Map (Map map JSONObject.fromObject(json);).
      Other Reactions
      1. I don't know for sure, as I haven't yet try to do so.
      2. Note, a previous comment I made on this subject was for a previous version of Gson.
      3. With the implementation of Gson issue 325, it may now work to just deserialize to Map.

    11. Gson and deserializing an array of objects with arrays in it

      This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is an array of object with an array of object}}". input.json Contents Foo.java This second example uses instead a JSON structure that is actually an array of TypeDTO object with an array of an array of ItemDTO object to match the originally provided Java data structure. details

      Reactions - Positive 3, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. import java.io.FileReader
      3. import java.util.ArrayList
      4. public class Foo {
      5. public static void main(String[] args) throws Exception {
      6. Gson gson = new Gson()
      7. TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class)
      8. System.out.println(gson.toJson(myTypes))
      9. }
      10. }
      11. class TypeDTO {
      12. int id
      13. String name
      14. ArrayList<ItemDTO> items
      15. }
      16. class ItemDTO {
      17. int id
      18. String name
      19. Boolean valid
      20. }

      Positive Reactions
      1. @Programmer Bruce +1 for saying "rather have one simple line of code".
      2. And when you need to optimise, GSON's streaming model does provide great performance increases.
      3. The power of GSON is not how fast it parses, but how fast it is to write and maintain the code required for a large number of production cases.
      Negative Reactions
      1. Thanks for your solution, after three hours of trying in vain, your method was the best I found.

    12. Gson and deserializing an array of objects with arrays in it

      input.json Contents Foo.java This second example uses instead a JSON structure that is actually an array of TypeDTO object with an array of an array of ItemDTO object to match the originally provided Java data structure. input.json Contents Foo.java Regarding the remaining two questions is Gson extremely fast. details

      Reactions - Positive 3, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. import java.io.FileReader
      3. import java.util.ArrayList
      4. public class Foo {
      5. public static void main(String[] args) throws Exception {
      6. Gson gson = new Gson()
      7. TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class)
      8. System.out.println(gson.toJson(myTypes))
      9. }
      10. }
      11. class TypeDTO {
      12. int id
      13. String name
      14. ArrayList<ItemDTO> items[]
      15. }
      16. class ItemDTO {
      17. int id
      18. String name
      19. Boolean valid
      20. }

      Positive Reactions
      1. @Programmer Bruce +1 for saying "rather have one simple line of code".
      2. And when you need to optimise, GSON's streaming model does provide great performance increases.
      3. The power of GSON is not how fast it parses, but how fast it is to write and maintain the code required for a large number of production cases.
      Negative Reactions
      1. Thanks for your solution, after three hours of trying in vain, your method was the best I found.

    13. How to convert String to JSONObject in Java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. public class TestObjectToJson {
      3. private int data1 = 100
      4. private String data2 = "hello"
      5. public static void main(String[] args) {
      6. TestObjectToJson obj = new TestObjectToJson()
      7. Gson gson = new Gson()
      8. //convert java object to JSON format String json = gson.toJson(obj)
      9. System.out.println(json)
      10. }
      11. }

  43. switch off scientific notation in Gson double serialization

    e.g. The above will render say 9.166666E-6 as 0.000009166666 . .. details

    1. GsonBuilder gsonBuilder = new GsonBuilder()
    2. gsonBuilder.registerTypeAdapter(Double.class, new JsonSerializer<Double>() { @Override public JsonElement serialize(final Double src, final Type typeOfSrc, final JsonSerializationContext context) { BigDecimal value = BigDecimal.valueOf(src)
    3. return new JsonPrimitive(value)
    4. } })
    5. gson = gsonBuilder.create()

  44. Convert the java class data into JSON format?

    None .. details

    1. // to prevent specified fields from being serialized or deserialized // (i.e. not include in JSON output
    2. or being set even if they were included) \@JsonIgnoreProperties({ "internalId", "secretKey" })

    • See Also (4)
    1. Convert Java Object to Json and Vice versa?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class)

    2. JSON array in GSON parses, but objects are empty

      I think I'd be annoyed if I came across this in production code because without understanding what was going on it could be confusing. With that caveat being said you can create a custom JsonDeserializer and use GsonBuilder Then your code would look like If it were me and I had JSON that wasn't what I needed it to be but wanted to use GSON to directly serialize/deserialize I'd create the Answer class as a wrapper that hid the details With the public getters/setters for Answer accessing the private RealAnswer. details

      Reactions - Positive 8, Negative 2, Others 0

      1. /** * Due to how our JSON is being provided we created an inner * class. **/ public class Answer { private RealAnswer answer
      2. private class RealAnswer { public String text
      3. } ...}

      Positive Reactions
      1. this is an epic answer.
      2. Thanks Brian!
      3. It works!
      4. since learnt from implementing backbone and gson that it is not that smart to do so.
      5. an update to your answer will be much appreciated.
      6. thanks a million.
      7. Glad I could help :).
      8. thanks again!.
      Negative Reactions
      1. But seems a tad weird, since i need to do this for all my files.
      2. unfortunately, there is no way i can change that output.
      Other Reactions
      1. @mingyeow - I added another section this morning.
      2. how do I tell GSON that I would like these to be recognized as Answer objects?
      3. btw, my inital json was implemented as such because of how Restkit in iOS expects this json.
      4. i "get" gson a lot better now.
      5. I figure I could probably specify something for GSON?
      6. got it.
      7. As noted, personally I'd not do it, but knowing it exists is in the spirit of SO.

    3. Understanding Ajax Simplifications in Spring 3.0 example

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. $.getJSON("account/availability", { name: $('#name').val() }

    4. Convert Java complex object to Json

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. MyComplexObject myComplexObject = gson.fromJson(jsonRepresentation, MyComplexObject.class)

  45. get json array from servlet using ajax

    None .. details

    1. $.ajax({ url : "SerlvetToJsp", dataType : 'json', contentType:"application/json", error : function() { alert("Error")
    2. }, success : function(data) { var data1=data[0], var data2=data[2], alert(data1[0])
    3. } })

    • See Also (4)
    1. Json Values from List<Map<String, Object>> in javascript emberjs

      Sorry for the complicated code but List<Map<String,Object is not a trivial data structure -). Ok then after the extensive comments and mavilein's comment here a jsbin to play with But basically as already mentioned here an example Edit To not mess around in the comments this is how you should do it Edit 2 To answer your last comment suppose you have a text area in your html markup with the id set to myTextArea then this is a way how you could do it Hope it helps. details

      Reactions - Positive 6, Negative 1, Others 0

      1. var myConcatenatedText = ""
      2. $.getJSON('/test', function(data) { // if data is an array of objects like [{...}, {...}] then data.forEach(function(item) { for(key in item) { myConcatenatedText += key + ", " item[key] + " - "
      3. console.log(key + ", " item[key])
      4. })
      5. $('#myTextArea').append(myConcatenatedText)
      6. })

      Positive Reactions
      1. Thank you very much, I will give that a go now!.
      2. @user2654214, please see my last edit (Edit 2) for an answer.
      3. Im new to ember and JSON,kind regards.
      4. you are welcome, glad to help out.
      5. well, this depends on the structure of the JSON object, but if it's a valid JSON then yes.
      6. Works brilliantly, thank you again.
      Negative Reactions
      1. Thank you, sorry for all questions.
      Other Reactions
      1. How do you append each of the objects to a text area.
      2. $.getJSON('/test', forEach(function(data){ for(key in data) { console.log(key + ", " data[key]); }) });.
      3. @user2654214, edited my answer to include the correction to your code example in the last comment.
      4. so could i do this?
      5. currently its only displaying the last element of the last object.
      6. Would this work in the same way if the JSON object was being returned to ember via a java method?

    2. Json Values from List<Map<String, Object>> in javascript emberjs

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. $.getJSON('/test', function(data) { // if data is an array of objects like [{...}, {...}] then data.forEach(function(item) { for(key in item) { console.log(key + ", " item[key])
      2. })
      3. })

    3. Gson: How to exclude specific fields from Serialization without annotations

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = gsonBuilder.excludeFieldsWithModifiers(Modifier.TRANSIENT).create()

    4. Parsing JSON W/ API Key

      I've also included a fully generic GsonSerializer so that it can be reused for other gson responses The way you would work with this class is as follows. This should give you enough that you can pretty much plug and play. details

      Reactions - Positive 0, Negative 0, Others 0

      1. // Where mData is a class of type T mData = (T) GsonSerializer.seralizeData(Json, mData)
      2. // or in a specific example mSystemList = (SystemList) GsonSerializer.seralizeData(Json, new SystemList())

      Other Reactions
      1. Just at work right now.
      2. will do once I get home.
      3. @JaisonBrooksDevelopment have updated.
      4. I've updated my code by using the GSON library, can you take a 2nd look at it.

  46. Gson: can we get the serialized field name in a type adapter?

    Let the code speak. Plus I declared a custom runtime exception These are the classes I used in the example This gives this stacktrace Unfortunately the EnumTypeAdapter does not know anything about the context it's called so this solution is not enough to catch the field name. .. details

    1. package stackoverflow.questions.q16715117
    2. import java.io.IOException
    3. import java.util.*
    4. import com.google.gson.*
    5. import com.google.gson.annotations.SerializedName
    6. import com.google.gson.reflect.TypeToken
    7. import com.google.gson.stream.*
    8. public class Q16715117 { public static void main(String[] args) { GsonBuilder gb = new GsonBuilder()
    9. gb.registerTypeAdapterFactory(CUSTOM_ENUM_FACTORY)
    10. Container c1 = new Container()
    11. Gson g = gb.create()
    12. String s1 = "{\"colour\":\"RED\",\"number\":42}"
    13. c1 = g.fromJson(s1, Container.class)
    14. System.out.println("Result: "+ c1.toString())
    15. } public static final TypeAdapterFactory CUSTOM_ENUM_FACTORY = newEnumTypeHierarchyFactory()
    16. public static TypeAdapterFactory newEnumTypeHierarchyFactory() { return new TypeAdapterFactory() { @SuppressWarnings({"rawtypes", "unchecked"}) public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Class<? super T> rawType = typeToken.getRawType()
    17. if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) { return null
    18. } if (!rawType.isEnum()) { rawType = rawType.getSuperclass()
    19. // handle anonymous subclasses } return (TypeAdapter<T>) new CustomEnumTypeAdapter(rawType)
    20. } }
    21. } private static final class CustomEnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> { private final Map<String, T> nameToConstant = new HashMap<String, T>()
    22. private final Map<T, String> constantToName = new HashMap<T, String>()
    23. private Class<T> classOfT
    24. public CustomEnumTypeAdapter(Class<T> classOfT) { this.classOfT = classOfT
    25. try { for (T constant : classOfT.getEnumConstants()) { String name = constant.name()
    26. SerializedName annotation = classOfT.getField(name).getAnnotation(SerializedName.class)
    27. if (annotation != null) { name = annotation.value()
    28. } nameToConstant.put(name, constant)
    29. constantToName.put(constant, name)
    30. } } catch (NoSuchFieldException e) { throw new AssertionError()
    31. } } public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull()
    32. return null
    33. } String nextString = in.nextString()
    34. T enumValue = nameToConstant.get(nextString)
    35. if (enumValue == null) throw new GsonEnumParsinException(nextString, classOfT.getName())
    36. return enumValue
    37. } public void write(JsonWriter out, T value) throws IOException { out.value(value == null ? null : constantToName.get(value))
    38. } }}

    Positive Reactions
    1. This works fine but is not exactly what I want (but it's what I've done in the end anyway...).
    2. thanks.
    Negative Reactions
    1. As I said I'd like to be able to know the attribute name, not the wrong enum value, not the enum name, but the class field name.
    Other Reactions
    1. Going to add some conclusions.
    2. Ok, edit to give also field names.
    3. You had the same conclusion I had some months ago and I decided to not copy this class in the end.

    • See Also (2)
    1. GSON GraphAdapterBuilder fails with interfaces

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.google.gson.graph
      2. import com.google.gson.Gson
      3. import com.google.gson.TypeAdapter
      4. import com.google.gson.TypeAdapterFactory
      5. import com.google.gson.reflect.TypeToken
      6. import com.google.gson.stream.JsonReader
      7. import com.google.gson.stream.JsonToken
      8. import com.google.gson.stream.JsonWriter
      9. import java.io.IOException
      10. import java.util.HashMap
      11. import java.util.Map
      12. /** * @author Giacomo Tesio */
      13. public class InterfaceAdapterFactory implements TypeAdapterFactory {
      14. final Map<String, GenericFunction<Gson, TypeAdapter<?>>> adapters
      15. private final Class<?> commonInterface
      16. public InterfaceAdapterFactory(Class<?> commonInterface, Class<?>[] concreteClasses) {
      17. this.commonInterface = commonInterface
      18. this.adapters = new HashMap<String, GenericFunction<Gson, TypeAdapter<?>>>()
      19. final TypeAdapterFactory me = this
      20. for (int i = 0 i < concreteClasses.length ++i) {
      21. final Class<?> clazz = concreteClasses[i]
      22. this.adapters.put(
      23. clazz.getName(),
      24. new GenericFunction<Gson, TypeAdapter<?>>() {
      25. public TypeAdapter<?> map(Gson gson) {
      26. TypeToken<?> type = TypeToken.get(clazz)
      27. return gson.getDelegateAdapter(me, type)
      28. }
      29. })
      30. }
      31. }
      32. public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
      33. final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type)
      34. if (!this.commonInterface.isAssignableFrom(type.getRawType())
      35. && !this.commonInterface.equals(type.getRawType())) {
      36. return delegate
      37. }
      38. final TypeToken<T> typeToken = type
      39. final Gson globalGson = gson
      40. return new TypeAdapter<T>() {
      41. public void write(JsonWriter out, T value) throws IOException {
      42. out.beginObject()
      43. out.name("@t")
      44. out.value(value.getClass().getName())
      45. out.name("@v")
      46. delegate.write(out, value)
      47. out.endObject()
      48. }
      49. @SuppressWarnings({"unchecked"})
      50. public T read(JsonReader in) throws IOException {
      51. JsonToken peekToken = in.peek()
      52. if (peekToken == JsonToken.NULL) {
      53. in.nextNull()
      54. return null
      55. }
      56. in.beginObject()
      57. String dummy = in.nextName()
      58. String typeName = in.nextString()
      59. dummy = in.nextName()
      60. TypeAdapter<?> specificDelegate = adapters.get(typeName).map(globalGson)
      61. T result = (T) specificDelegate.read(in)
      62. in.endObject()
      63. return result
      64. }
      65. }
      66. }
      67. }

    2. How can I get Gson to use accessors rather than fields?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.common.base.CaseFormat
      2. import com.google.gson.Gson
      3. import com.google.gson.TypeAdapter
      4. import com.google.gson.reflect.TypeToken
      5. import com.google.gson.stream.JsonReader
      6. import com.google.gson.stream.JsonWriter
      7. import java.io.IOException
      8. import java.lang.reflect.Method
      9. public class AccessorBasedTypeAdaptor<T> extends TypeAdapter<T> {
      10. private Gson gson
      11. public AccessorBasedTypeAdaptor(Gson gson) {
      12. this.gson = gson
      13. }
      14. @SuppressWarnings("unchecked")
      15. @Override
      16. public void write(JsonWriter out, T value) throws IOException {
      17. out.beginObject()
      18. for (Method method : value.getClass().getMethods()) {
      19. boolean nonBooleanAccessor = method.getName().startsWith("get")
      20. boolean booleanAccessor = method.getName().startsWith("is")
      21. if ((nonBooleanAccessor || booleanAccessor)
      22. && !method.getName().equals("getClass")
      23. && method.getParameterTypes().length == 0) {
      24. try {
      25. String name = method.getName().substring(nonBooleanAccessor ? 3 : 2)
      26. name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, name)
      27. Object returnValue = method.invoke(value)
      28. if (returnValue != null) {
      29. TypeToken<?> token = TypeToken.get(returnValue.getClass())
      30. TypeAdapter adapter = gson.getAdapter(token)
      31. out.name(name)
      32. adapter.write(out, returnValue)
      33. }
      34. } catch (Exception e) {
      35. throw new ConfigurationException("problem writing json: ", e)
      36. }
      37. }
      38. }
      39. out.endObject()
      40. }
      41. @Override
      42. public T read(JsonReader in) throws IOException {
      43. throw new UnsupportedOperationException("Only supports writes.")
      44. }
      45. }

  47. Gson: can we get the serialized field name in a type adapter?

    Plus I declared a custom runtime exception These are the classes I used in the example This gives this stacktrace Unfortunately the EnumTypeAdapter does not know anything about the context it's called so this solution is not enough to catch the field name. Edit So you have to use also another TypeAdapter that I called CustomReflectiveTypeAdapterFactory and is almost a copy of CustomReflectiveTypeAdapterFactory and I changed a bit the exception so The most important part is read method where I catch the exception and add the field name and throw again exception. .. details

    1. public final class CustomReflectiveTypeAdapterFactory implements TypeAdapterFactory { private final ConstructorConstructor constructorConstructor
    2. private final FieldNamingStrategy fieldNamingPolicy
    3. private final Excluder excluder
    4. public CustomReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy fieldNamingPolicy, Excluder excluder) { this.constructorConstructor = constructorConstructor
    5. this.fieldNamingPolicy = fieldNamingPolicy
    6. this.excluder = excluder
    7. } public boolean excludeField(Field f, boolean serialize) { return !excluder.excludeClass(f.getType(), serialize) && !excluder.excludeField(f, serialize)
    8. } private String getFieldName(Field f) { SerializedName serializedName = f.getAnnotation(SerializedName.class)
    9. return serializedName == null ? fieldNamingPolicy.translateName(f) : serializedName.value()
    10. } public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) { Class<? super T> raw = type.getRawType()
    11. if (!Object.class.isAssignableFrom(raw)) { return null
    12. // it's a primitive! } ObjectConstructor<T> constructor = constructorConstructor.get(type)
    13. return new Adapter<T>(constructor, getBoundFields(gson, type, raw))
    14. } private CustomReflectiveTypeAdapterFactory.BoundField createBoundField( final Gson context, final Field field, final String name, final TypeToken<?> fieldType, boolean serialize, boolean deserialize) { final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType())
    15. // special casing primitives here saves ~5% on Android... return new CustomReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) { final TypeAdapter<?> typeAdapter = context.getAdapter(fieldType)
    16. @SuppressWarnings({"unchecked", "rawtypes"}) // the type adapter and field type always agree @Override void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException { Object fieldValue = field.get(value)
    17. TypeAdapter t = new CustomTypeAdapterRuntimeTypeWrapper(context, this.typeAdapter, fieldType.getType())
    18. t.write(writer, fieldValue)
    19. } @Override void read(JsonReader reader, Object value) throws IOException, IllegalAccessException { Object fieldValue = null
    20. try { fieldValue = typeAdapter.read(reader)
    21. } catch (GsonEnumParsinException e){ e.setFieldName(field.getName())
    22. throw e
    23. } if (fieldValue != null || !isPrimitive) { field.set(value, fieldValue)
    24. } } }
    25. } // more copy&paste code follows

    Positive Reactions
    1. This works fine but is not exactly what I want (but it's what I've done in the end anyway...).
    2. thanks.
    Negative Reactions
    1. As I said I'd like to be able to know the attribute name, not the wrong enum value, not the enum name, but the class field name.
    Other Reactions
    1. Going to add some conclusions.
    2. Ok, edit to give also field names.
    3. You had the same conclusion I had some months ago and I decided to not copy this class in the end.

  48. Struts2 How to Return a JSON Response

    Try using the response's PrintWriter. Java . .. details

    1. public String execute() { Gson gson = new Gson()
    2. String jsonString = gson.toJson(audioTaggingService.findTagsByName(q))
    3. HttpServletResponse response = ServletActionContext.getResponse()
    4. response.setContentType("application/json")
    5. response.getWriter().write(jsonString )
    6. return null
    7. }

    Positive Reactions
    1. This is the most correct answer here given that he already has a JSON string.
    Other Reactions
    1. A better approach would be to create an actual Result to handle dealing with the HttpServletResponse, though.

  49. Java object with variable-dimensional array

    You'll need to have your own custom trunk/gson/docs/javadocs/com/google/gson/JsonDeserializer.html JsonDeserializer since the coordinates variable doesn't have a set of defined array dimensions. I recommend using an interface for the shape then writing a deserializer for it like so Then implementations for each type. .. details

    1. public interface Shape {
    2. ShapeType getType()
    3. enum ShapeType {
    4. Polygon,
    5. MultiPolygon
    6. }
    7. }

    • See Also (2)
    1. Java object with variable-dimensional array

      I recommend using an interface for the shape then writing a deserializer for it like so Then implementations for each type. ShapeType.Polygon And ShapeType.MultiPolygon Then lastly your deserializer will rely on the type from each implementation Using this you can also create other implementations based on the type of shape and add them to the switch to support them. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class PolygonShape implements Shape {
      2. private final ShapeType type = ShapeType.Polygon
      3. private double[][][] coordinates
      4. public ShapeType getType() {
      5. return type
      6. }
      7. public double[][][] getCoordinates() {
      8. return coordinates
      9. }
      10. public void setCoordinates(double[][][] coordinates) {
      11. this.coordinates = coordinates
      12. }
      13. }

    2. Java object with variable-dimensional array

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class MultiPolygonShape implements Shape {
      2. private final ShapeType type = ShapeType.MultiPolygon
      3. private double[][][][] coordinates
      4. public ShapeType getType() {
      5. return type
      6. }
      7. public double[][][][] getCoordinates() {
      8. return coordinates
      9. }
      10. public void setCoordinates(double[][][][] coordinates) {
      11. this.coordinates = coordinates
      12. }
      13. }

  50. Java object with variable-dimensional array

    None .. details

    1. GsonBuilder builder
    2. // ...builder.registerTypeAdapter(Shape.class, new ShapeDeserializer())

    • See Also (9)
    1. Parsing GSON Google Places API

      Otherwise there is really faster but slightly less obvious to use or configure libraries like Jackson-Json . Hey man thank you very much the way that I was calling was wrong...Instead of that now I'm calling like this . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new GsonBuilder().serializeNulls().create()
      2. GoogleMapper mapper = gson.fromJson(retorno.toString(), GoogleMapper.class)

      Other Reactions
      1. Why do you keep on calling the ritorno.toString() method?

    2. GSON Expected BEGIN_ARRAY but was BEGIN_OBJECT

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new GsonBuilder() .registerTypeAdapter(ProjectContainer.class, new MyDeserializer()) .build()
      2. ProjectContainer pContainer = gson.fromJson(myJson, ProjectContainer.class)

    3. incorrect gson code: Expected BEGIN_OBJECT but was STRING

      Implement InstanceCreator<Resp and JsonDeserializer<Resp to your resp and collection. Register Type adapter in GsonBuilder and Parse your json context in deserialize method. details

      Reactions - Positive 0, Negative 0, Others 0

      1. GsonBuilder builder = new GsonBuilder()
      2. builder.registerTypeAdapter()

      Other Reactions
      1. "How do I register Type adapter there?"
      2. Look here: URL_http://google - gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html.
      3. Resp is just a string, Should I implement these two interfaces at the class where I am using resp?
      4. How do I register Type adapter there?
      5. No ,the just collection or your class VideoImages.
      6. GsonBuilder is inside jar file.

    4. Serialize java object with GSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Person p = new Person(1, "Joe", new Person(2, "Mike"))
      2. com.google.gson.Gson gson = new GsonBuilder().registerTypeAdapter(Person.class, new PersonSerializer()) .create()
      3. System.out.println(gson.toJson(p))

    5. How to serialize a class with an interface?

      1. Create serialiser/deserialiser 2 make Gson use it for the interface type of your choice . details

      Reactions - Positive 1, Negative 1, Others 0

      1. Gson gson = new GsonBuilder().registerTypeAdapter(Animal.class, new InterfaceAdapter<Animal>()) .create()

      Positive Reactions
      1. That looks like a clean solution to me.
      Negative Reactions
      1. StackOverflow exception -- context.serialize(object) calls itself.
      Other Reactions
      1. Next time I need to do this, I'll give it a whirl.
      2. Don't know how that worked for you.

    6. Polymorphism with gson

      GSON has a pretty good test case here showing how to define and register a type hierarchy adapter. a/com/google/gson/functional/TypeHierarchyAdapterTest.java?r=739 om/google/gson/functional/TypeHierarchyAdapterTest.java?r=739 To use that do this Serialize method of the adapter can be a cascading if-else check of what type it is serializing. details

      Reactions - Positive 0, Negative 0, Others 0

      1. gson = new GsonBuilder() .registerTypeAdapter(BaseQuestion.class, new BaseQuestionAdaptor()) .create()

    7. Gson: How to exclude specific fields from Serialization without annotations

      Here is what your ExclusionStrategy should look like If you see closely it returns true for Student.firstName and Country.name which is what you want to exclude. You need to apply this ExclusionStrategy like this This returns "middleName":"J. details

      Reactions - Positive 4, Negative 3, Others 0

      1. Gson gson = new GsonBuilder() .setExclusionStrategies(new TestExclStrat()) //.serializeNulls() <-- uncomment to serialize NULL fields as well .create()
      2. Student src = new Student()
      3. String json = gson.toJson(src)
      4. System.out.println(json)

      Positive Reactions
      1. It should be generic enough to apply to every class that has a property named country of the Country class.
      2. you mean null value or empty string.
      3. You may get even more creative, but I kept it elemental.
      4. Thank you for you answer.
      Negative Reactions
      1. What I;m trying to see if it's possible to know where in the object graph I am when the method it called so I can exclude some fields of country but not countryOfBirth(for example) so same class but different properties.
      2. I don't want to create an ExclusionStrategy for every class.
      3. How can I exclude empty fields?
      Other Reactions
      1. What I want is to create an ExclusionStrategy that can take a string like country.name and only exlude the field name when serializing the field country.
      2. I've edited my question to clarify what I'm trying to achieve.
      3. Didn't get what do you mean by empty.
      4. Ty for the update.
      5. I have the same question than @ykartal.
      6. That takes generic approach.
      7. Is there a way to exclude fields which has empty values?
      8. @Liviu T. I have updated the answer.

    8. Gson: How to exclude specific fields from Serialization without annotations

      See below Here is how we can use it generically. It returns "firstName":"Philip","middleName":"J. details

      Reactions - Positive 4, Negative 3, Others 0

      1. Gson gson = new GsonBuilder() .setExclusionStrategies(new TestExclStrat("in.naishe.test.Country.name")) //.serializeNulls() .create()
      2. Student src = new Student()
      3. String json = gson.toJson(src)
      4. System.out.println(json)

      Positive Reactions
      1. It should be generic enough to apply to every class that has a property named country of the Country class.
      2. you mean null value or empty string.
      3. You may get even more creative, but I kept it elemental.
      4. Thank you for you answer.
      Negative Reactions
      1. What I;m trying to see if it's possible to know where in the object graph I am when the method it called so I can exclude some fields of country but not countryOfBirth(for example) so same class but different properties.
      2. I don't want to create an ExclusionStrategy for every class.
      3. How can I exclude empty fields?
      Other Reactions
      1. What I want is to create an ExclusionStrategy that can take a string like country.name and only exlude the field name when serializing the field country.
      2. I've edited my question to clarify what I'm trying to achieve.
      3. Didn't get what do you mean by empty.
      4. Ty for the update.
      5. I have the same question than @ykartal.
      6. That takes generic approach.
      7. Is there a way to exclude fields which has empty values?
      8. @Liviu T. I have updated the answer.

    9. How to solve circular reference in json serializer caused by hibernate bidirectional mapping?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { public boolean shouldSkipClass(Class<?> clazz) { return (clazz == B.class)
      2. } /** * Custom field exclusion goes here */ public boolean shouldSkipField(FieldAttributes f) { return false
      3. } }) /** * Use serializeNulls method if you want To serialize null values * By default, Gson does not serialize null values */ .serializeNulls() .create()

  51. JsonReader Exception in Android while parsing large josn data

    I have a concearn that the short circuit and doesn't execute the reader.peek(). I have a concearn with the short circuit and the check for reader.peek not executing.Do the reader.peek check first then go over your ifs Good Luck . .. details

    1. if (reader.peek()!=JsonToken.NULL) {if (name.equals("om_id")) { String om_id = reader.nextString()
    2. } else if (name.equals("om_multiselect")) { String om_multiselect = reader.nextString()
    3. } else if (name.equals("omlang_name")) { String omlang_name = reader.nextString()
    4. } else if (name.equals("om_createdDate")) { String om_createdDate = reader.nextString()
    5. } else { reader.skipValue()
    6. }

  52. Get Data from JSON String

    AlGallaf alert(data.name[0]) worked for me also. For the browsers that don't you can implement it using json2.js.Most browsers support JSON.parse() hope this will help you for detail see link . .. details

    1. //sample code var json = '{"result":true,"count":1}', obj = JSON.parse(json)
    2. alert(obj.count)

  53. How to add ArrayList&lt;String&gt; to JSON Array - keeping type safty in mind

    If you're looking for good Generics support try Google-Gson . Here's how you would go about serializing your generic ArrayList with Gson Here's how you would deserialize the same JSON string with its Generics intact . .. details

    1. Gson gson = new Gson()
    2. ArrayList<String> arrayList= (ArrayList<String>) ClassName.getArrayList()
    3. // Serializing to a JSON element nodeJsonElement jsonElement = gson.toJsonTree(arrayList)
    4. System.out.println(jsonElement.isJsonArray())
    5. // true// Or, directly to JSON stringString json = gson.toJson(arrayList)
    6. System.out.println(json)

  54. Having errors on parsing JSON

    None .. details

    1. /** In here i'm getting the error */ new ListViewLoaderTask().execute(strJson.toString())

    • See Also (3)
    1. Play Framework 2.1 Cannot handle JSON POST request from controller

      I had exactly the same issue. Besides the dataType you have to set contentType as well as the original poster suggested . details

      Reactions - Positive 0, Negative 0, Others 0

      1. var jsonMsg = JSON.stringify(msg)
      2. jsRoutes.controllers.Application.sendJson().ajax({ type : 'POST', dataType : 'json', contentType : 'application/json
      3. charset=utf-8', data : jsonMsg})

      Other Reactions
      1. related question: URL_http://stackoverflow.com/questions/19941786/playframework - handling-post-reqeust.

    2. Consume REST services on Android, easiest way?

      Spring Android has a RestTemplate that is pretty easy to use. rest-template.html android/docs/1.0.x/reference/html/rest-template.html For example . details

      Reactions - Positive 0, Negative 0, Others 0

      1. String url = "http://mypretendservice.com/events"
      2. RestTemplate restTemplate = new RestTemplate()
      3. Event[] events = restTemplate.getForObject(url, Event[].class)

    3. Ignore specific field on serialization with Jackson

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @JsonIgnoreProperties({"foobar"})public static class Foo { public String foo = "a"
      2. public String bar = "b"
      3. public String foobar = "c"
      4. }//Test codeObjectMapper mapper = new ObjectMapper()
      5. Foo foo = new Foo()
      6. foo.foobar = "foobar"
      7. foo.foo = "Foo"
      8. String out = mapper.writeValueAsString(foo)
      9. Foo f = mapper.readValue(out, Foo.class)

  55. Expected BEGIN_OBJECT but was BEGIN_ARRAY

    Its List<Page would now match against the Page[ objects that were shown deserialized above. Now if you extend your Page class with Threads as well The whole JSON would deserialize successfully. .. details

    1. PageResponse pageResp = gson.fromJson("{ pages : " + pageJson.toString() + " }", PageResponse.class)
    2. System.out.println(pageResp.getPages().get(1).getPage())
    3. // 1

    Positive Reactions
    1. @EmmanuelCortes Works for me.
    2. I've figured it out!
    3. Take a look if you like.
    4. @EmmanuelCortes Thanks for accepting.
    5. Thanks for all your help!!!
    6. Thanks you so much.
    Negative Reactions
    1. Sorry, I forgot you don't have all of the JSON, but the just println(pageResp) itself give me a NullPointerException.
    2. Ah, sorry about that.
    3. In your source Where you initialized pageResp you have " "{ pages :" but on here you have "{ response :".
    4. I missed updating.
    5. My use of PageResponse[] was incorrect though.
    6. Here's my [source code]( URL_http://pastebin.com/jkMTgL3w ) and my [data.json]( URL_http://pastebin.com/eX5wYZ5k ) file.
    Other Reactions
    1. I don't have the complete JSON with me.
    2. pages.length returns 16 instead of 2.
    3. I've tested and covered all the cases (including nested threads) now.
    4. My two pages are identical.
    5. I get a NullPointerException on every pageResp println() I run.
    6. !.
    7. Fixed it for future reference.
    8. getJSONObject(0) would give you the first page object which would give 0 for a getPage() call.
    9. @EmmanuelCortes That's because I only replicated the first page as page:1 again (just changed its index).

    • See Also (3)
    1. Action to accept dynamic json data from user interface

      You may do it with a simple jquery ajax call where you could specify the content-type and dataType. Add json plugin to the project dependencies with json-lib-2.3-jdk15.jar. details

      Reactions - Positive 0, Negative 0, Others 0

      1. $.ajax({ type: "POST", url: "/the/action/url", data : {}, dataType:"JSON", contentType: "application/json
      2. charset=utf-8"})

    2. GSON: Expected BEGIN_OBJECT but was STRING

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. BusinessPartnerCreate bpc = gson.fromJson(obj.get("business-partner-create"), BusinessPartnerCreate.class)

    3. Using a JSON web service from a Java client application

      If you want easier you could use HtmlUnit which imitates the behaviour of browsers so you could easily get the content and parse it into Html javascript and css you could also execute javascript code on content so you could probably parse JSON files to using JSON.parse or any other equivalent functions of any page on the web. so for HtmlUnit here is a sample code but it maybe rather heavy for your requirements so a highly recommend the use of HttpClient library.I'm sure you could find many JSON libraries for java but here is one for you json-lib . details

      Reactions - Positive 2, Negative 0, Others 0

      1. WebClient wc = new WebClient(BrowserVersion.FIREFOX_3_6)
      2. HtmlPage page = wc.getPage("http://urlhere")
      3. page.executeJavaScript("JS code here")

      Positive Reactions
      1. Thanks, I'll check out those.
      2. Then the HttpClient library suits you best.
      Other Reactions
      1. It's the HTTP communication and extracting the JSON out of it which I'm trying to solve without reinventing the wheel.
      2. Also, see URL_http://www.json.org/java/ .
      3. I already have the JSON parsing under control (the application also reads and parses local JSON files).

  56. Does Gson have something like WRITE_NULL_MAP_VALUES (Jackson)?

    None .. details

    1. public static Gson createGson() { return new GsonBuilder().registerTypeAdapter(Map.class, new NullSerializingMapSerializer()).create()
    2. }public class NullSerializingMapSerializer implements JsonSerializer<Map> { private static final Gson gson = (new GsonBuilder()).serializeNulls().create()
    3. public JsonElement serialize(Map map, Type typeOfSrc, JsonSerializationContext context) { if(map == null) { return JsonNull.INSTANCE
    4. } return new JsonPrimitive(gson.toJson(map))
    5. }}

  57. How to unwrap and serialize java map in java using jackson?

    None .. details

    1. { //belongs to dataMap1 "key1": { "fieldOne": "some value", "fieldTwo": "some value" }, "key2": { "fieldOne": "some value", "fieldTwo": "some value" }, //belongs to dataMap2 "key3": { "fieldOne": "some value", "fieldTwo": "some value" }, "key4": { "fieldOne": "some other value", "fieldTwo": "some other value" }}

    • See Also (2)
    1. What is the key of a JSON-encoded String

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. var obj = jQuery.parseJSON('"Succes!"')
      2. alert(obj)

    2. How to decode a json string with gson in java?

      I've searched but any results work for me.Thank you. Standard way of object de-serialization is the following For primitives corresponding class should be used instead of MyType. details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. MyType obj = gson.fromJson(json, MyType.class)

  58. Spring - @RequestBody blocks the requets?

    There was also missing comma and wrong quotation marks. Here is the corrected version . .. details

    1. var jsonData = { "name" : "XXX", "age" : "20", "hobby" : "TV"}
    2. $.ajax({ type : 'POST', dataType : 'json', url : "sender.html", contentType : "application/json", data : JSON.stringify(jsonData), success : function(data, textStatus) { alert("success")
    3. $("#result").html(data.name + data.age + data.hobby)
    4. }})

  59. Google URL shortening API not working in Java

    The thing you are trying to achieve can be done by the following code. This code would directly allow you to use the Google URL shortening web service You have to make some changes in your original code and you are done . .. details

    1. public static String shortenUrl(String longUrl) { @SuppressWarnings("unused") OAuthService oAuthService = new ServiceBuilder().provider(GoogleApi.class).apiKey("anonymous").apiSecret("anonymous") .scope("https://www.googleapis.com/auth/urlshortener") .build()
    2. OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, "https://www.googleapis.com/urlshortener/v1/url")
    3. oAuthRequest.addHeader("Content-Type", "application/json")
    4. String json = "{\"longUrl\": \"http://"+longUrl+"/\"}"
    5. oAuthRequest.addPayload(json)
    6. Response response = oAuthRequest.send()
    7. Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType()
    8. Map<String, String> responseMap = new GsonBuilder().create().fromJson(response.getBody(), typeOfMap)
    9. String st=responseMap.get("id")
    10. return st
    11. }

    Positive Reactions
    1. thanks... this works :).

    • See Also (1)
    1. Jackson - Deserialize Generic class variable

      The different approaches and examples use hundreds of lines of code so I've omitted reposting them here. . details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class GsonInstanceCreatorForParameterizedTypeDemo { public static void main(String[] args) { Id<String> id1 = new Id<String>(String.class, 42)
      2. Gson gson = new GsonBuilder().registerTypeAdapter(Id.class, new IdInstanceCreator()).create()
      3. String json1 = gson.toJson(id1)
      4. System.out.println(json1)
      5. // actual output: {"classOfId":{},"value":42} // This contradicts what the Gson docs say happens. // With custom serialization, as described in a // previous Gson user guide section, // intended output may be // {"value":42} // input: {"value":42} String json2 = "{\"value\":42}"
      6. Type idOfStringType=new TypeToken<Id<String>>(){}.getType()
      7. Id<String> id1Copy = gson.fromJson(json2, idOfStringType)
      8. System.out.println(id1Copy)
      9. // output: classOfId=class java.lang.String, value=42 Type idOfGsonType = new TypeToken<Id<Gson>>() {}.getType()
      10. Id<Gson> idOfGson = gson.fromJson(json2, idOfGsonType)
      11. System.out.println(idOfGson)
      12. // output: classOfId=class com.google.gson.Gson, value=42 } } class Id<T> { private final Class<T> classOfId
      13. private final long value
      14. public Id(Class<T> classOfId, long value) { this.classOfId = classOfId
      15. this.value = value
      16. } @Override public String toString() { return "classOfId=" + classOfId + ", value=" + value
      17. } } class IdInstanceCreator implements InstanceCreator<Id<?>> { @SuppressWarnings({ "unchecked", "rawtypes" }) public Id<?> createInstance(Type type) { Type[] typeParameters = ((ParameterizedType) type).getActualTypeArguments()
      18. Type idType = typeParameters[0]
      19. return new Id((Class<?>) idType, 0L)
      20. } }

  60. How to convert json objects with number as field key in Java?

    If you can't change it you have to deserialize it to Map. Example source code could looks like this Above program prints . .. details

    1. import com.google.gson.Gson
    2. import com.google.gson.GsonBuilder
    3. import com.google.gson.reflect.TypeToken
    4. import java.lang.reflect.Type
    5. import java.util.HashMap
    6. import java.util.Map
    7. public class GsonProgram {
    8. public static void main(String... args) throws Exception {
    9. Gson gson = new GsonBuilder().create()
    10. String json =
    11. "{\"1\":{\"id\":\"1\",\"value\":\"something\"},\"2\":{\"id\":\"2\",\"value\":\"some other thing\"}}"
    12. Type type = new TypeToken<HashMap<String, HashMap<String, String>>>() {}.getType()
    13. Map<String, Map<String, String>> map = gson.fromJson(json, type)
    14. for (Map<String, String> data : map.values()) {
    15. System.out.println(Data.fromMap(data))
    16. }
    17. }
    18. }
    19. class Data {
    20. private int id
    21. private String value
    22. public int getId() {
    23. return id
    24. }
    25. public void setId(int id) {
    26. this.id = id
    27. }
    28. public String getValue() {
    29. return value
    30. }
    31. public void setValue(String value) {
    32. this.value = value
    33. }
    34. @Override
    35. public String toString() {
    36. return "Data [id=" + id + ", value=" + value + "]"
    37. }
    38. public static Data fromMap(Map<String, String> properties) {
    39. Data data = new Data()
    40. data.setId(new Integer(properties.get("id")))
    41. data.setValue(properties.get("value"))
    42. return data
    43. }
    44. }

    Positive Reactions
    1. Thanks anyway.
    Negative Reactions
    1. Thanks, but my json object is way more complex which requires to construct a corresponding class.
    Other Reactions
    1. But I've found out a raw way to read json object which only picks up the fields I need.

  61. Using The Google Maps Geolocation API

    None .. details

    1. { "homeMobileCountryCode": 310, "homeMobileNetworkCode": 410, "radioType": "gsm", "carrier": "Vodafone", "cellTowers": [ // See the Cell Tower Objects section below. ], "wifiAccessPoints": [ // See the WiFi Access Point Objects section below. ]}

    • See Also (1)
    1. Spring @RequestBody containing a list of different types (but same interface)

      The annotations go on the Animal base class. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. @JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
      2. @JsonSubTypes({
      3. @JsonSubTypes.Type(value = Dog.class, name = "Dog"),
      4. @JsonSubTypes.Type(value = Cat.class, name = "Cat")
      5. })
      6. public abstract class Animal {}

      Positive Reactions
      1. This works!
      2. Thank you very much!.

  62. What would be the best way to create association in a list (array) of arbitrary things?

    None .. details

    1. public enum PartOfSpeach { NOUN, VERB, // in USA "verb" includes all nouns, because any noun can be "verbed" ADJECTIVE, ADVERB}

    • See Also (1)
    1. Create a JSONArray

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. object = gson.fromJson(json, ClassName.class)

  63. serializing java object to json with auto generated names

    Can you show us your User class. Let's take Gson as example you may use Gson customize serializer like following I create class Users otherwise other List will use MySerializer which is not expected Another simple way is put list into map and then make json like . .. details

    1. import com.google.common.collect.Lists
    2. import com.google.gson.*
    3. import java.lang.reflect.Type
    4. import java.util.ArrayList
    5. import java.util.List
    6. public class Test {
    7. public static class User {
    8. private List<Integer> ids
    9. private List<String> names
    10. public User(List<Integer> ids, List<String> names) {
    11. this.ids = ids
    12. this.names = names
    13. }
    14. }
    15. public static class Users extends ArrayList<User> {}
    16. public static void main(String[] args) {
    17. Users users = new Users()
    18. users.add(
    19. new User(Lists.newArrayList(1, 2, 3), Lists.newArrayList("anton", "berta", "charlie")))
    20. users.add(
    21. new User(Lists.newArrayList(4, 5, 6), Lists.newArrayList("dora", "emil", "friedrich")))
    22. GsonBuilder gsonBuilder = new GsonBuilder()
    23. gsonBuilder.registerTypeAdapter(Users.class, new MySerializer())
    24. System.out.printf(gsonBuilder.create().toJson(users))
    25. }
    26. public static class MySerializer implements JsonSerializer<Users> {
    27. @Override
    28. public JsonElement serialize(
    29. Users users, Type type, JsonSerializationContext jsonSerializationContext) {
    30. JsonObject jsonObject = new JsonObject()
    31. for (int i = 0 i < users.size() i++) {
    32. jsonObject.add(String.valueOf(i + 1), jsonSerializationContext.serialize(users.get(i)))
    33. }
    34. return jsonObject
    35. }
    36. }
    37. }

  64. how to create a login with java and json web service

    thank you. try adding And check if the response has an entity . .. details

    1. request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")))

    • See Also (4)
    1. Parse Json In Java How to read Inner Value

      Create a class which have variables you want to read from json string.And Gson will handle the rest. gson/ Example usage . details

      Reactions - Positive 0, Negative 0, Others 0

      1. //convert the json string back to objectDataObject obj = gson.fromJson(br, DataObject.class)

      Other Reactions
      1. First Review the Question m not looking how to parse there is some issue while parsing.

    2. How to manipulate leaves of a JSON tree

      I just found by going through all 3435 rarewords. Here's a straight forward approach in C++ strike>This assumes you wanted to do replacements on all string values and only matches whole strings. details

      Reactions - Positive 6, Negative 3, Others 0

      1. #include <fstream>#include "JSON.hpp"#include <boost/algorithm/string/regex.hpp>#include <boost/range/adaptors.hpp>#include <boost/phoenix.hpp>static std::vector<std::wstring> readRareWordList(){ std::vector<std::wstring> result
      2. std::wifstream ifs("testcases/rarewords.txt")
      3. std::wstring line
      4. while (std::getline(ifs, line)) result.push_back(std::move(line))
      5. return result
      6. }struct RareWords : boost::static_visitor<> { ///////////////////////////////////// // do nothing by default template <typename T> void operator()(T&&) const { /* leave all other things unchanged */ } ///////////////////////////////////// // recurse arrays and objects void operator()(JSON::Object& obj) const { for(auto& v : obj.values) { //RareWords::operator()(v.first)
      7. /* to replace in field names (?!) */ boost::apply_visitor(*this, v.second)
      8. } } void operator()(JSON::Array& arr) const { int i = 0
      9. for(auto& v : arr.values) { if (i++) // skip the first element in all arrays boost::apply_visitor(*this, v)
      10. } } ///////////////////////////////////// // do replacements on strings void operator()(JSON::String& s) const { using namespace boost
      11. const static std::vector<std::wstring> rareWords = readRareWordList()
      12. const static std::wstring replacement = L"__RARE__"
      13. for (auto&& word : rareWords) if (word == s.value) s.value = replacement
      14. }}
      15. int main(){ auto document = JSON::readFrom(std::ifstream("testcases/test3.json"))
      16. boost::apply_visitor(RareWords(), document)
      17. std::cout << document
      18. }

      Positive Reactions
      1. Okay, glad to hear it works.
      2. And if some array is like ["xyz.","xyz."
      3. +1 for code, Thanks!
      4. I just noticed that the problem changed from 'string matching' to 'wordlist set membership tetsting' so it could be much more efficient using a (hash) set: URL_https://github.com/sehe/spirit-v2-json/blob/16093940/test.cpp .
      5. Yeah reading the words form a file is pretty trivial.
      6. Thank you!
      Negative Reactions
      1. For some reason, it is complaining on apply_visitor "function couldn't be resolved".
      2. or for example S. U.S.A. A* that was messing up with String.replaceAll Regex matching .
      3. But, I will still accept your answer to give you credit for your hard work.
      Other Reactions
      1. I am going to modify question to draw tree for more clarity.
      2. Fixing it.
      3. Yes, exact matches of whole string.
      4. I gave up setting up C++ env.
      5. Since I don't know much C++.
      6. For example: if "xyz."
      7. I will accept this answer after trying the updated code.
      8. Another drawback of replaceAll method was that it could potentially replace the first string.
      9. should be replaced with "_RARE_" not even "xyz".
      10. I figured out Java way of doing it.
      11. Going to try this now.. will be back in 10-15 min.
      12. I can share whole input and rareWord file if you need.
      13. is in rare word list, then only "xyz."
      14. ", "_RARE_"] ... notice that second string in branch array getting replaced, we never touch the first one.
      15. ] it should be ["xyz.
      16. However, I'd really want exact examples on what to match (do you always want _exact matches_ of _whole strings_?
      17. EDIT also skipping the first element in every array now (see comment) and removed the regex matching that I picked from your code, but wasn't what you wanted after all.
      18. @Watt updated with readRareWordList() and showing how to do exact matches only.
      19. Actually, I tried to shorten my question for readability, in real my rareword list contains 3435 words and some of them contanis .
      20. Will it possible you can modify your code, so that I can pass rareWords through a file?

    3. GSON: how to prevent StackOverflowError while keeping circular references?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class Person { @GsonRepellent private String lastName = "Troscianko"
      2. // ...

    4. How do I create a multidimensional HashMap or Hashtable in JSP / Java and convert it to a JSON object?

      I appreciate your help. try this . details

      Reactions - Positive 4, Negative 0, Others 0

      1. for (int i=0
      2. i < 10
      3. i++){ numbers.put("Number",i)
      4. numbers.put("Numberx2",i*2)
      5. arr[i] = new Hashtable()
      6. arr[i].put("Comp",numbers)
      7. }results_hash.put("results",arr)

      Positive Reactions
      1. I will take a look at the other solutions, as well.
      2. This worked great, except that the last result is stored 10 times (i.e Number=9, Numberx2=18) in the JSON object.
      3. So, thank you again.
      4. Thank you, though.
      Other Reactions
      1. I modified your example a bit and received the desired result for the exercise.
      2. I don't understand why your solution doesn't produce the desired result, though.
      3. Code: Hashtable results_hash new Hashtable(); Hashtable numbers[] new Hashtable[10]; Hashtable[] arr new Hashtable[10]; for (int i=0; i < 10; i++) { numbers[i] new Hashtable(); numbers[i].put("Number",i); numbers[i].put("Numberx2",i*2); arr[i] new Hashtable(); arr[i].put("Comp",numbers[i]); } results_hash.put("results",arr);.

  65. Unable to parse Json array using Gson

    None .. details

    1. string Json="some Json String"
    2. JavaScriptSerializer Js = new JavaScriptSerializer()
    3. MapData ObjMapDat = new MapData ()
    4. ObjMapDat =Js.Deserialize<MapData>(Json)

    • See Also (4)
    1. NullPointerException : JSON Parsing in JAVA using GSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. ListTeleServices teleservices = gson.fromJson(br, ListTeleServices.class)

    2. Serialization and Deserialization with Jackson Exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class Container {
      2. private AAnimal animal
      3. public AAnimal getAnimal() {
      4. return animal
      5. }
      6. @JsonTypeInfo(
      7. use = JsonTypeInfo.Id.NAME,
      8. include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
      9. property = "type"
      10. )
      11. @JsonSubTypes({@Type(value = Cat.class, name = "cat"), @Type(value = Dog.class, name = "dog")})
      12. public void setAnimal(AAnimal animal) {
      13. this.animal = animal
      14. }
      15. }
      16. public abstract class AAnimal {
      17. public String name
      18. }

    3. GSON not calling my TypeAdapter for a type which is an interface

      This will serialize your type using the adapter. Alternatively you can register the PlayerTypeAdapter for MagicPlayer.class and your existing code will work. details

      Reactions - Positive 0, Negative 1, Others 0

      1. gson.toJson(bean, Player.class)

      Negative Reactions
      1. It doesn't exactly solve the problem or make GSON usable in any way, because relying on the code to tell it the type of everything is never going to work.
      Other Reactions
      1. e.g., there is another place where I have a List where each object could be any type.
      2. The second part of the question explains what to do.
      3. Now what am I supposed to do?
      4. For each concrete type you need to register the TypeAdapter you want to use.
      5. This answers the main part of the question about why it doesn't work.

    4. Jackson : custom collection serialization to JSON

      What you can do is to introduce another class. . details

      Reactions - Positive 1, Negative 1, Others 0

      1. class MyClass implements MyInterface {
      2. private MyOtherClass myclass
      3. }
      4. class MyOtherClass {
      5. private String value = "test"
      6. }

      Positive Reactions
      1. Thank you.
      Negative Reactions
      1. That is what I was trying to avoid, because I'm using a legacy class model (I can not modify it), but I need to obtain that JSON format (also a restriction imposed by a third party system).
      Other Reactions
      1. you can wrap the legacy class model for the purpose of serialization.

  66. Parser for JSON in Servlet just like SAX for XML

    There is also Jackson . You can do it with GSON Note If you are using android api 11 then you can use the classes instead of GSON. .. details

    1. import com.google.gson.stream.JsonReader
    2. import com.google.gson.stream.JsonToken
    3. import java.io.IOException
    4. import java.math.BigDecimal
    5. public class JsonProcessor {
    6. public void parse(JsonReader reader) throws IOException {
    7. onStartDocument()
    8. while (true) {
    9. JsonToken token = reader.peek()
    10. switch (token) {
    11. case BEGIN_ARRAY:
    12. reader.beginArray()
    13. onBeginArray()
    14. break
    15. case END_ARRAY:
    16. reader.endArray()
    17. onEndArray()
    18. break
    19. case BEGIN_OBJECT:
    20. reader.beginObject()
    21. onBeginObject()
    22. break
    23. case END_OBJECT:
    24. reader.endObject()
    25. onEndObject()
    26. break
    27. case NAME:
    28. String name = reader.nextName()
    29. onName(name)
    30. break
    31. case STRING:
    32. String s = reader.nextString()
    33. onString(s)
    34. break
    35. case NUMBER:
    36. String n = reader.nextString()
    37. onNumber(new BigDecimal(n))
    38. break
    39. case BOOLEAN:
    40. boolean b = reader.nextBoolean()
    41. onBoolean(b)
    42. break
    43. case NULL:
    44. reader.nextNull()
    45. onNull()
    46. break
    47. case END_DOCUMENT:
    48. onEndDocument()
    49. return
    50. }
    51. }
    52. }
    53. public void onStartDocument() {}
    54. public void onBeginObject() {}
    55. public void onEndObject() {}
    56. public void onBeginArray() {}
    57. public void onEndArray() {}
    58. public void onName(String name) {}
    59. public void onNumber(BigDecimal n) {}
    60. public void onString(String s) {}
    61. public void onNull() {}
    62. public void onEndDocument() {}
    63. public void onBoolean(boolean b) {}
    64. }

    • See Also (5)
    1. Java Built-in data parser for JSON or XML or else

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. IRule linkRule = new DefaultRule(Type.CHARACTER, "/rss/channel/item/link") { @Override public void handleParsedCharacters(XMLParser parser, String text, Object userObject) { // Also store the link, or something equivalently fancy }}

    2. Java Built-in data parser for JSON or XML or else

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. Classname xyz = gson.fromJson(JSONedString, Classname.class)

    3. Smallest (less internal code), up-to-spec JSON parser in Java

      All you have to do is make a class with a structure that matches a JSON object and converting JSON can be as simple as If there's something more complex you need to do you only need to add some field annotations or write a custom serializer/deserializer which is pretty easy and register it once. Actually converting JSON to objects is always just a matter of calling . details

      Reactions - Positive 1, Negative 1, Others 0

      1. gson.fromJson(...)

      Positive Reactions
      1. It's very nice :).
      Negative Reactions
      1. I am sorry I was not clear, see my edit.
      Other Reactions
      1. I didn't know about Google Gson.

    4. Convert XML to JSON format

      It's really easy to convert between xml-to-object json-to-object object-to xml and object-to-json. Here's an example from XStream's-docs XML POJO DTO) Convert from XML to POJO And then from POJO to JSON Note although the method reads XStream will produce JSON since the Jettison driver is used. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class Person { private String firstname
      2. private String lastname
      3. private PhoneNumber phone
      4. private PhoneNumber fax
      5. // ... constructors and methods}

    5. Convert a JSON string to object in Java?

      Since it uses Java Reflection to create proxies I'm thinking it won't work. Also it's currently got a hard dependency on Google Collections which I want to remove and it's probably too heavyweight for your needs but it allows you to interact with your JSON data in the way you're looking for . details

      Reactions - Positive 1, Negative 0, Others 0

      1. interface Foo { String getName()
      2. int getWidth()
      3. int getHeight()
      4. }Foo myFoo = Fixjure.of(Foo.class).from(JSONSource.newJsonString("{ name : \"foo name\" }")).create()
      5. String name = myFoo.getName()
      6. // name now .equals("foo name")

      Positive Reactions
      1. Amazing, though I don't want Foo, just the native Object.

  67. How to deserialize a LIST using GSON or another JSON to Java?

    Another way is to use an array as a type e.g. This way you avoid all the hassle with the Type object and if you really need a list you can always convert the array to a list e.g. .. details

    1. Video[] videoArray = gson.fromJson(json, Video[].class)

    • See Also (3)
    1. How to exclude null-value fields when using Flexjson?

      Adding the Transformer by Path vs by Class is not supported as FlexJSON forces TypeTransformer for null values JSONContext.java line 95 . I am a newbie,i had same problem and could not find any solution on source forge so i used regular expression to remove all the nulls from JSON String . details

      Reactions - Positive 0, Negative 0, Others 0

      1. /** * This Function removes all the key:value pairs from the Json String for which the value equals null * @param jsonStringWithNullKeys * @return jsonStringWithoutNullKeys */public static String getJsonStringWithoutNullKeys(String jsonStringWithNullKeys){ Pattern p = Pattern.compile( "([,]?\"[^\"]*\":null[,]?)+" )
      2. Matcher m = p.matcher( jsonStringWithNullKeys )
      3. StringBuffer newString = new StringBuffer( jsonStringWithNullKeys.length() )
      4. while( m.find() ) { if( m.group().startsWith( "," ) & m.group().endsWith( "," ) ) m.appendReplacement( newString, "," )
      5. else m.appendReplacement( newString, "" )
      6. } m.appendTail( newString )
      7. return newString.toString()
      8. }

    2. How to check whether the given object is object or Array in JSON string

      Or This is recommended. . details

      Reactions - Positive 1, Negative 3, Others 0

      1. if (json instanceof Array) { // get JSON array} else { // get JSON object}

      Positive Reactions
      1. This is one way though not recommended.
      Negative Reactions
      1. Yep, if you hit an exception trying to get an object when it is a JSON array, then you provide the implementation to get an array in the catch clause.
      2. I am concerned about checking the contents of the object and checking whether URL is array or an object.
      3. Thanks, I know how to remove exceptions.
      Other Reactions
      1. Actually I am looking for a function which can be used in if condition for the check.

    3. Convert JSON String to Java Object or HashMap

      It has excellent support for generics and fullworthy Javabeans and really eases the conversion task. In library-to-encode-decode-from-json-to-java-util-map/2496528#2496528 this answer you can find an example to convert a Map<String String to JSON and vice versa and in json-to-java/1688182#1688182 this-answer another example to convert a JSON string to a fullworthy Javabean from Javabean to JSON is pretty simple with . details

      Reactions - Positive 0, Negative 0, Others 0

      1. gson.toJson(bean)

  68. How do you get GSON to omit null or empty objects and empty arrays and lists?

    Null values are excluded by default as long as you don't set serializeNulls to your GsonBuilder. A way for empty Lists is to register a JsonSerializer Then register it . .. details

    1. class CollectionAdapter implements JsonSerializer<Collection<?>> { @Override public JsonElement serialize(Collection<?> src, Type typeOfSrc, JsonSerializationContext context) { if (src == null || src.isEmpty()) // exclusion is made here return null
    2. JsonArray array = new JsonArray()
    3. for (Object child : src) { JsonElement element = context.serialize(child)
    4. array.add(element)
    5. } return array
    6. }}

  69. Gson deserialize json with varying value types

    We have to create it to avoid deserialization loop tricky part). And now we can test our solution with test method . .. details

    1. GsonBuilder builder = new GsonBuilder()
    2. builder.registerTypeAdapter(Profile.class, new ProfileJsonDeserializer())
    3. Gson gson = builder.create()
    4. JsonEntity jsonEntity = gson.fromJson(new FileReader("/tmp/json.txt"), JsonEntity.class)
    5. System.out.println(jsonEntity)

    Positive Reactions
    1. Thank you both very much for the help!.
    Negative Reactions
    1. This did the trick, since manual parsing would have been a large task as you suspected @MikO.
    Other Reactions
    1. @Meatje: this is the other possibility I talked about in my comment...

    • See Also (2)
    1. Reading multiple elements from json file

      input.json JacksonFoo.java Output Update A similar solution using Gson. GsonFoo.java . details

      Reactions - Positive 0, Negative 2, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.GsonBuilder
      3. import com.google.gson.JsonStreamParser
      4. import java.io.FileReader
      5. public class GsonFoo {
      6. public static void main(String[] args) throws Exception {
      7. Gson gson = new GsonBuilder().create()
      8. JsonStreamParser parser = new JsonStreamParser(new FileReader("input.json"))
      9. while (parser.hasNext()) {
      10. System.out.println(gson.fromJson(parser.next(), Thing.class))
      11. }
      12. }
      13. }

      Negative Reactions
      1. I just assumed "Stream" referred to parsing JSON one streaming token at a time, as opposed to binding JSON data to objects/arrays.
      2. This post is incorrect.
      Other Reactions
      1. It's called JsonStreamParser and the documentation is here: URL_http://google-gson.googlecode .
      2. Gson does have that (mis)feature.
      3. Updated answer accordingly.
      4. Ah, neat.
      5. I was thrown by the use of the word "Stream" in the GSON API.
      6. com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonStreamParser.html.

    2. Parsing JSON maps / dictionaries with Gson?

      This example also demonstrates using a FieldNamingStrategy to avoid specifying the serialized name for every field provided that the field-to-element name mapping is consistent. . details

      Reactions - Positive 2, Negative 1, Others 0

      1. import java.io.FileReader
      2. import java.lang.reflect.Field
      3. import java.util.Map
      4. import com.google.gson.FieldNamingStrategy
      5. import com.google.gson.Gson
      6. import com.google.gson.GsonBuilder
      7. public class Foo{ public static void main(String[] args) throws Exception { GsonBuilder gsonBuilder = new GsonBuilder()
      8. gsonBuilder.setFieldNamingStrategy(new MyFieldNamingStrategy())
      9. Gson gson = gsonBuilder.create()
      10. Egg egg = gson.fromJson(new FileReader("input.json"), Egg.class)
      11. System.out.println(gson.toJson(egg))
      12. }}class Egg{ private String mKey1
      13. private String mKey2
      14. private Map<String, String> mKey3
      15. }class MyFieldNamingStrategy implements FieldNamingStrategy{ //Translates the Java field name into its JSON element name representation. @Override public String translateName(Field field) { String name = field.getName()
      16. char newFirstChar = Character.toLowerCase(name.charAt(1))
      17. return newFirstChar + name.substring(2)
      18. }}

      Positive Reactions
      1. The example Egg class that I used is probably not complete enough for purposes other than Gson serialization/deserialization.
      2. I see, it creates a Map property and then I can implement my own get methods that basically just grab the value from the Map for a corresponding key.
      Negative Reactions
      1. The example I posted uses the custom FieldNamingStrategy to specify the serialized names of the JSON elements: that they are the same as the Java field names changed to not have the starting 'm' and changed so that the second character of the Java field name is made lower case and used as the first character of the JSON element name.
      Other Reactions
      1. Do you maybe not actually want a Map on the Java side, but instead have an object along the lines that Zuljin suggested?
      2. Those are the keys in the Map.
      3. The Egg class could certainly be defined to have a method such as public Map getKey3() {return mKey3;}.
      4. For some reason I thought you were suggesting that I still use a subclass but it implements Map.
      5. Right.
      6. I was just demonstrating what's necessary for Gson purposes.
      7. How would you implement a Map in this case while specifying the serialized name?
      8. But how do I define get/set methods to access childKey1, childKey2, and childKey3?
      9. The serialized name of what?
      10. That makes sense.
      11. Why would you want to have a setter method for the Map keys?
      12. What would it do?
      13. Oh I see.
      14. I'm not sure what you're asking.
      15. Are you asking about how to get all of the keys in a Map?
      16. I need to be able to get those properties out individually, so I need public access.

  70. Gson deserialize json with varying value types

    None .. details

    1. class ProfileJsonDeserializer implements JsonDeserializer<Profile> {
    2. @Override
    3. public Profile deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
    4. throws JsonParseException {
    5. if (jsonElement.isJsonPrimitive()) {
    6. return null
    7. }
    8. return context.deserialize(jsonElement, JsonProfile.class)
    9. }
    10. }
    11. class JsonProfile extends Profile {}

  71. create json file dynamicly with hierarcy data

    It defines mapping between property name and name in JSON. Please see my example I have written this example using source code from this question Create-JSON-file-with-deep-array . .. details

    1. import com.google.gson.FieldNamingStrategy
    2. import com.google.gson.Gson
    3. import com.google.gson.GsonBuilder
    4. import java.lang.reflect.Field
    5. import java.util.ArrayList
    6. import java.util.HashMap
    7. import java.util.List
    8. import java.util.Map
    9. public class GsonProgram {
    10. public static void main(String... args) throws Exception {
    11. Entry entry1 = new Entry()
    12. entry1.setId(1)
    13. entry1.setType("USER")
    14. entry1.setProperty("Salary")
    15. Entry entry2 = new Entry()
    16. entry2.setId(2)
    17. entry2.setType("EMP")
    18. Entry entry3 = new Entry()
    19. entry3.setId(2)
    20. entry3.setType("EMP")
    21. entry3.setProperty("Work")
    22. Entry entry4 = new Entry()
    23. entry4.setId(2)
    24. entry4.setType("EMP")
    25. EntryListContainer entryListContainer = new EntryListContainer()
    26. ArrayList<Entry> entryList1 = new ArrayList<Entry>()
    27. ArrayList<Entry> entryList2 = new ArrayList<Entry>()
    28. entryList1.add(entry1)
    29. entryList1.add(entry2)
    30. entryList2.add(entry3)
    31. entryList2.add(entry4)
    32. entryListContainer.setEntryList1(entryList1)
    33. entryListContainer.setEntryList2(entryList2)
    34. Map<String, String> mapping = new HashMap<String, String>()
    35. mapping.put("entryList1", "customer")
    36. mapping.put("entryList2", "Address")
    37. Gson gson =
    38. new GsonBuilder()
    39. .serializeNulls()
    40. .setFieldNamingStrategy(new DynamicFieldNamingStrategy(mapping))
    41. .create()
    42. System.out.println(gson.toJson(entryListContainer))
    43. }
    44. }
    45. class DynamicFieldNamingStrategy implements FieldNamingStrategy {
    46. private Map<String, String> mapping
    47. public DynamicFieldNamingStrategy(Map<String, String> mapping) {
    48. this.mapping = mapping
    49. }
    50. @Override
    51. public String translateName(Field field) {
    52. String newName = mapping.get(field.getName())
    53. if (newName != null) {
    54. return newName
    55. }
    56. return field.getName()
    57. }
    58. }
    59. class EntryListContainer {
    60. private List<Entry> entryList1
    61. private List<Entry> entryList2
    62. public void setEntryList1(List<Entry> entryList1) {
    63. this.entryList1 = entryList1
    64. }
    65. public List<Entry> getEntryList1() {
    66. return entryList1
    67. }
    68. public void setEntryList2(List<Entry> entryList2) {
    69. this.entryList2 = entryList2
    70. }
    71. public List<Entry> getEntryList2() {
    72. return entryList2
    73. }
    74. }
    75. class Entry {
    76. private int id
    77. private String type
    78. private String property
    79. public void setId(int id) {
    80. this.id = id
    81. }
    82. public int getId() {
    83. return id
    84. }
    85. public void setType(String type) {
    86. this.type = type
    87. }
    88. public String getType() {
    89. return type
    90. }
    91. public String getProperty() {
    92. return property
    93. }
    94. public void setProperty(String property) {
    95. this.property = property
    96. }
    97. }

    Positive Reactions
    1. I'm glad I could help you.
    2. Thanks Micha,I think I need to try to implement it manually and then find the gaps.Thanks again!.
    3. I'll try to help you as best as I can.
    4. Thanks mykhaylo ,I will use your provided solution,one question that im not sure that I fully understand is why do i need to provide "entry1List" and 2 also in the code mapping.put("entryList1", "customer"); in my code I can have 1..n entry list not just one or two... mapping.put("entryList2", "Address");.
    5. Please, provide better explanation what you have and what you need to do with classes which you have.
    Other Reactions
    1. Do you mean for instance that the entityListContiner can be with one list and every time i will add new instance with the name of the entry?
    2. If you have more than 2 properties you should define all of it in this mapping.
    3. For example if you have class with two lists you have to create one mapping, if you have class with three lists you have to create new one for it.
    4. Im asking this since you hardcode in entityListContiner two entries,entryList1@entryList2 but I can get lot of entrylist's...
    5. This mappings defines which property names should be changed in JSON.
    6. I'm not sure that I understand your question.
    7. Each instance you can configure with different mappings.
    8. You can build so many instances of Gson class as you want.

    • See Also (2)
    1. How to access nested elements of json object using getJSONArray method

      It allows to parse JSON string into object data model. Please see my example Program output If you not familiar with this library then you can find a lot of informations in Gson-User-Guide . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.GsonBuilder
      3. import com.google.gson.annotations.SerializedName
      4. import java.util.ArrayList
      5. import java.util.Arrays
      6. import java.util.List
      7. public class GsonProgram {
      8. public static void main(String... args) {
      9. String response =
      10. "{\"result\":{\"map\":{\"entry\":[{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentA\"},\"value\":\"fsdf\"},{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentB\"},\"value\":\"dfdf\"}]}}}"
      11. Gson gson = new GsonBuilder().serializeNulls().create()
      12. Response res = gson.fromJson(response, Response.class)
      13. System.out.println("Entries: " + res.getResult().getMap().getEntry())
      14. }
      15. }
      16. class Response {
      17. private Result result
      18. public Result getResult() {
      19. return result
      20. }
      21. public void setResult(Result result) {
      22. this.result = result
      23. }
      24. @Override
      25. public String toString() {
      26. return result.toString()
      27. }
      28. }
      29. class Result {
      30. private MapNode map
      31. public MapNode getMap() {
      32. return map
      33. }
      34. public void setMap(MapNode map) {
      35. this.map = map
      36. }
      37. @Override
      38. public String toString() {
      39. return map.toString()
      40. }
      41. }
      42. class MapNode {
      43. List<Entry> entry = new ArrayList<Entry>()
      44. public List<Entry> getEntry() {
      45. return entry
      46. }
      47. public void setEntry(List<Entry> entry) {
      48. this.entry = entry
      49. }
      50. @Override
      51. public String toString() {
      52. return Arrays.toString(entry.toArray())
      53. }
      54. }
      55. class Entry {
      56. private Key key
      57. private String value
      58. public String getValue() {
      59. return value
      60. }
      61. public void setValue(String value) {
      62. this.value = value
      63. }
      64. public Key getKey() {
      65. return key
      66. }
      67. public void setKey(Key key) {
      68. this.key = key
      69. }
      70. @Override
      71. public String toString() {
      72. return "[key=" + key + ", value=" + value + "]"
      73. }
      74. }
      75. class Key {
      76. @SerializedName("$")
      77. private String value
      78. @SerializedName("@xsi.type")
      79. private String type
      80. public String getValue() {
      81. return value
      82. }
      83. public void setValue(String value) {
      84. this.value = value
      85. }
      86. public String getType() {
      87. return type
      88. }
      89. public void setType(String type) {
      90. this.type = type
      91. }
      92. @Override
      93. public String toString() {
      94. return "[value=" + value + ", type=" + type + "]"
      95. }
      96. }

    2. Java JSON Object Flattening

      I've used GSON very briefly and I think it does what you're looking for. While investigating it I knocked up the following ludicrously simple example to confirm it was as simple as I needed first a POJO Then the worker class No xml descriptors or custom converters needed. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.GsonBuilder
      3. import java.util.ArrayList
      4. import java.util.List
      5. public class Main {
      6. public static void main(String[] args) {
      7. Main m = new Main()
      8. m.execute(args)
      9. }
      10. private void execute(String[] args) {
      11. Gson gson = new GsonBuilder().setPrettyPrinting().create()
      12. Member member = new Member()
      13. List<String> stuff = new ArrayList<String>()
      14. stuff.add("shoes")
      15. stuff.add("hat")
      16. member.setStuff(stuff)
      17. member.setName("Bert")
      18. member.setAge(21)
      19. String output = gson.toJson(member, Member.class)
      20. log(output)
      21. Member member2 = gson.fromJson(output, Member.class)
      22. log(member2.getName())
      23. }
      24. private void log(String text) {
      25. System.out.println(text)
      26. }
      27. }

      Other Reactions
      1. your example model is not composed of any other domain objects.
      2. how does it flatten the model?

  72. How to validate request parameter if it is not a bean in spring MVC?

    Providing a wrapper bean is a good practice. Then the Request Body should be listOfLongs 123,456,789] . .. details

    1. class LongList { @NotEmpty private List<Long> listOfLongs
    2. // Setters and Getters ...}

  73. Custom json serialization tweak

    None .. details

    1. public class MDataSerializer implements JsonSerializer<MData> {
    2. @Override
    3. public JsonElement serialize(MData src, Type typeOfSrc, JsonSerializationContext context) {
    4. JsonObject obj = new JsonObject()
    5. obj.addProperty("version", src.version)
    6. obj.addProperty("ttl", src.ttl)
    7. for (Foo foo : src.foos) {
    8. obj.addProperty(foo.getKey(), foo.getValue())
    9. }
    10. return obj
    11. }
    12. }

    • See Also (1)
    1. How to properly convert List of specific objects to Gson?

      However everything has started to work properly when I have read carefully my error. Finally I have registered type adapter in this way Any my MessageAdapter class looks like And thats all. details

      Reactions - Positive 1, Negative 0, Others 0

      1. public class MessageAdapter implements JsonSerializer<Message> {
      2. @Override
      3. public JsonElement serialize(Message message, Type type, JsonSerializationContext jsc) {
      4. JsonObject jsonObject = new JsonObject()
      5. jsonObject.addProperty("message_id", message.getMessageId())
      6. jsonObject.addProperty("message", message.getMessage())
      7. jsonObject.addProperty("user", message.getUsers().getUsername())
      8. jsonObject.addProperty("date", message.getDate().toString())
      9. return jsonObject
      10. }
      11. }

      Positive Reactions
      1. Thanks a lot woyaru..
      Other Reactions
      1. :).
      2. I had similar issue but got through it by creating a custom JsonSerializer.

  74. GSON Expected BEGIN_ARRAY but was BEGIN_OBJECT

    If there's only one object for project it's returning only an object instead of an array. MikO's answer solves the problem but another approach is encapsulating that logic in a custom deserializer Then you can use . .. details

    1. class MyDeserializer implements JsonDeserializer<ProjectContainer> {
    2. @Override
    3. public ProjectContainer deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
    4. throws JsonParseException {
    5. JsonObject jo = je.getAsJsonObject().getAsJsonObject("project")
    6. if (jo.isJsonArray()) {
    7. return new Gson().fromJson(je, ProjectContainer.class)
    8. } else {
    9. Project p = jdc.deserialize(jo, Project.class)
    10. List<Project> pList = new ArrayList<Project>(1)
    11. pList.add(p)
    12. ProjectContainer pc = new ProjectContainer()
    13. pc.setProjects(pList)
    14. return pc
    15. }
    16. }
    17. }

    • See Also (2)
    1. Map JSONArray to object by position

      Note I haven't tested this or anything but at the very least it should put you on the path if you wanted to go this route. . details

      Reactions - Positive 4, Negative 0, Others 0

      1. class OuterObject {
      2. String build
      3. List<InnerObject> objectList = new ArrayList<InnerObject>()
      4. }
      5. class InnerObject {
      6. int field1, field2, field3, field4, field5, field6, field7, field8
      7. public InnerObject(
      8. int[]
      9. params) { // assign params accordingly }}class MyDeserializer implements JsonDeserializer<OuterObject> { @Override public OuterObject deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException { OuterObject oo = new OuterObject()
      10. JsonObject jo = je.getAsJsonObject()
      11. oo.build = jo.get("build").getAsString()
      12. JsonArray innerObjArrays = jo.getAsJsonArray("list")
      13. for (JsonElement e : innerObjArrays) {
      14. JsonArray innerArray = e.getAsJsonArray()
      15. // This is ugly but should give you the gist InnerClass ic = new InnerClass((int[])jdc.deserialize(innerArray, int[].class))
      16. oo.objectList.add(ic)
      17. }
      18. return oo
      19. }
      20. }

      Positive Reactions
      1. Thanks!
      2. Cool - edited to reflect that.
      3. Glad I could help!.
      4. I had to tweak things a little bit (build should be jo.get("build").getAsString()) but you provided a great starting point.

    2. JSON to Java: How to model lists of objects into generic object class whose object name from json is variable

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.JsonArray
      2. import com.google.gson.JsonDeserializationContext
      3. import com.google.gson.JsonDeserializer
      4. import com.google.gson.JsonElement
      5. import com.google.gson.JsonObject
      6. import com.google.gson.JsonParseException
      7. import java.lang.reflect.Type
      8. import java.util.ArrayList
      9. import java.util.List
      10. import java.util.Map
      11. class ProgramsDeserializer implements JsonDeserializer<List<Program>> {
      12. @Override
      13. public List<Program> deserialize(JsonElement e, Type type, JsonDeserializationContext jdc)
      14. throws JsonParseException {
      15. List<Program> programs = new ArrayList<>(10)
      16. JsonObject root = e.getAsJsonObject()
      17. for (Map.Entry<String, JsonElement> entry : root.entrySet()) {
      18. String id = entry.getKey()
      19. String title = ""
      20. String description = ""
      21. JsonElement arrayElement = entry.getValue()
      22. if (arrayElement.isJsonArray()) {
      23. JsonArray array = arrayElement.getAsJsonArray()
      24. JsonElement objectElement = array.get(0)
      25. if (objectElement.isJsonObject()) {
      26. JsonObject object = objectElement.getAsJsonObject()
      27. title = object.get("t").getAsString()
      28. description = object.get("d").getAsString()
      29. }
      30. }
      31. programs.add(new Program(id, title, description))
      32. }
      33. return programs
      34. }
      35. }

  75. GSON Expected BEGIN_ARRAY but was BEGIN_OBJECT

    I don't know too much about Jersey so I can't help you with that That said I can suggest a workaround using manually parsing in Gson to adapt your parsing to the 2 different responses object or array). You could do something like this Note that you don't need your class ProjectContainer. .. details

    1. //manually parsing until get the "project" element...JsonParser parser = new JsonParser()
    2. JsonObject rootObejct = parser.parse(yourJsonString).getAsJsonObject()
    3. JsonElement projectElement = rootObejct.get("project")
    4. Gson gson = new Gson()
    5. List<Project> projectList = new ArrayList<>()
    6. //Check if "project" element is an array or an object and parse accordingly...if (projectElement.isJsonObject()) { //The returned list has only 1 element Project project = gson.fromJson(projectElement, Project.class)
    7. projectList.add(project)
    8. }else if (projectElement.isJsonArray()) { //The returned list has >1 elements Type projectListType = new TypeToken<List<Project>>() {}.getType()
    9. projectList = gson.fromJson(projectElement, projectListType)
    10. }//Now you have a List<Project> projectList with one or many Project elements, //depending on the response...

    Positive Reactions
    1. Thank you.
    2. @Brian, obviously the web service is not responding correctly, that's for sure, but if the mapping to JSON is made by Jersey automatically...
    3. I really appreciate you help @MikO, the links that you have provided are very helpful, I prefer fixing the serialization issue of Jersey more than working around with parsing in Gson.
    4. Thank you again I really appreciated your help.
    Negative Reactions
    1. There's not a "problem" with Jersey or Gson ... the web service is basically broken and not returning consistently.
    2. Oh wait, I see what you mean - I misread that.
    3. where is the service broken?!
    4. The problem must be in Jersey's serialization...
    5. Otherwise, where is the error, if he doesn't have any serialization code?!
    6. @Brian, yes in my answer I clearly said that the problem is with Jersey... and looking at the JSON responses the method getPagedProjects seems for me to be returning correctly, otherwise he wouldn't get that data... and it must be returning a List or even the IDE would be complaining... so, again, there is a problem with Jersey, and in the links I have provided they seem to have the same problem...
    Other Reactions
    1. His Java class has a List and that's what it has to be in the JSON (an array) if it's going to map properly.
    2. Unknown - it depends on what getPagedProjects is returning.
    3. I thought you meant on the Gson side.
    4. I guess there is indeed some "problem" (or strange behaviour) in Jersey mapping...
    5. The web service is responding two different ways depending on the number of Project objects.

  76. JSON string from Gson: remove double quotes

    This will throw an error if you're not looking at a string but if you are you'll get the string value. Here's a test program to demonstrate And its output . .. details

    1. import com.google.gson.JsonElement
    2. import com.google.gson.JsonParser
    3. public class Test {
    4. public static void main(String[] args) {
    5. String in = "{\"hello\":\"world\"}"
    6. System.out.println(in)
    7. JsonElement root = new JsonParser().parse(in)
    8. System.out.println(root.getAsJsonObject().get("hello").toString())
    9. System.out.println(root.getAsJsonObject().get("hello").getAsString())
    10. }
    11. }

    Positive Reactions
    1. :-) JAXB is cool, but I think I'd do discription.substring(1, discription.length()-1) before converting JSON into XML just for the output.
    2. You answer however is simpler than mine.
    Other Reactions
    1. Our answer are both relevant.

  77. JSON string from Gson: remove double quotes

    Anyone able to tell me how i can get rid of the double qoutation marks. It's not documented properly but gets you a string that represents the JSON element and would be appropriate for re-creating the JSON serialization. .. details

    1. JsonElement#toString()

    Positive Reactions
    1. :-) JAXB is cool, but I think I'd do discription.substring(1, discription.length()-1) before converting JSON into XML just for the output.
    2. You answer however is simpler than mine.
    Other Reactions
    1. Our answer are both relevant.

    • See Also (6)
    1. JSON string from Gson: remove double quotes

      It's not documented properly but gets you a string that represents the JSON element and would be appropriate for re-creating the JSON serialization. What you want is . details

      Reactions - Positive 2, Negative 0, Others 0

      1. JsonElement#getAsString()

      Positive Reactions
      1. :-) JAXB is cool, but I think I'd do discription.substring(1, discription.length()-1) before converting JSON into XML just for the output.
      2. You answer however is simpler than mine.
      Other Reactions
      1. Our answer are both relevant.

    2. How to convert a String to JsonObject using gson library

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonElement jelem = gson.fromJson(json, JsonElement.class)
      2. JsonObject jobj = jelem.getAsJsonObject()

    3. JSON_encoded String to Java JSONObject

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. for(int i=0
      2. i<arrays.size()
      3. i++){ JsonElement e =arrays.get(i)
      4. artikli k = new artikli()
      5. k=gson.fromJson(e,artikli.class)
      6. System.out.println(k.toString())
      7. }

    4. Hamcrest Matcher with junit style diff

      EDIT But this would give me Notice that the only difference is in id:1 and id:2 but junit shows me different ordering in JSON as part of the error as well. The best i could do so far This gives me . details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Overrideprotected void describeMismatchSafely(JsonElement expectedJson, Description mismatchDescription) { mismatchDescription.appendValue(expectedJson).appendText("\ndifference:\n")
      2. try { assertEquals(expectedJson.toString(), originalJson.toString())
      3. } catch (ComparisonFailure e) { String message = e.getMessage()
      4. message = message.replace("expected:", "")
      5. message = message.replace("but was:", "")
      6. message = message.replaceFirst(">", ">\n")
      7. mismatchDescription.appendText(message)
      8. }}

    5. Java Play framework parsing JSON error

      I suspect you don't get the JSON answer but a http redirect code in your call to the web service. Two possibilites 1 Change the web service call to this probably solves your problem failing that 2 Change the line into something like and report back on the contents of the answer which gets logged in the second line. details

      Reactions - Positive 1, Negative 1, Others 0

      1. JsonElement rpxJson = rpxRequest.get().getJson()

      Positive Reactions
      1. thank you very much!
      Negative Reactions
      1. that was the problem but sorry I couldn't +1 your answer because of my reputation.
      Other Reactions
      1. yes, finally :).
      2. I think now you should be able to :).

    6. Java Play framework parsing JSON error

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. HttpResponse httpResponse = rpxRequest.get()
      2. Logger.log ( httpResponse.getString() )
      3. if ( httpResponse.success() ) { JsonElement rpxJson = httpResponse.getJson()
      4. } else { // fail gracefully}

  78. Deserializing JSON to non-static nested classes using Gson

    You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it. Anyway if it's actually possible deserialize to a non-static inner class your problem would be that First you are parsing the JSON with your class Tweet with which should be working since the class Tweet matches the JSON response. .. details

    1. Tweet tweet = gson.fromJson(string, Tweet.class)

    Positive Reactions
    1. Thanks a lot!
    2. Now everything works fine even with non-static inner class.

    • See Also (6)
    1. JSON to java object using gson

      If you want to include some transient fields You may want to try Also since its a inner class you may need to change your JSON If you can As noted here in this deserializing-arbitrary-object-json-arrays-in-inner-classes-with-gson-or nested post . The issue is that in your code you're passing SiteWrapper.class when you should be passing Site.class to gson.fromJSON This line should be Site is the class you defined for the JSON provided. details

      Reactions - Positive 0, Negative 1, Others 0

      1. Site s = gson.fromJSON(json, Site.class)

      Negative Reactions
      1. Statics are excluded by default.
      Other Reactions
      1. While this is certainly contributing to the issue, this will not work by itself.

    2. JSON to java object using gson

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. SiteWrapper m = gson.fromJson(json, SiteWrapper.class)

    3. Canonicalizing JSON files

      Note that in Ruby 1.8 symbols cannot be sorted so you have to call to_s in your sort. If your data consists of an array of objects or nested objects you'll need to create sorted hashes recursively . details

      Reactions - Positive 0, Negative 0, Others 0

      1. require 'rubygems'require 'json'require 'active_support/ordered_hash'obj = { :fig => false, :bananas => false, :apples => true, :eggplant => true, :cantaloupe => true, :dragonfruit => false}def sorted_hash(hsh) sorted_keys = hsh.keys.sort_by { |k| k.to_s } sorted_keys.inject(ActiveSupport::OrderedHash.new) do |o_hsh, k| o_hsh[k] = hsh[k] o_hsh endendputs JSON.pretty_generate(obj)# Could output in any order, depending on version of Ruby# {# "eggplant": true,# "cantaloupe": true,# "dragonfruit": false,# "fig": false,# "bananas": false,# "apples": true# }puts JSON.pretty_generate(sorted_hash(obj))# Always output in the same order# {# "apples": true,# "bananas": false,# "cantaloupe": true,# "dragonfruit": false,# "eggplant": true,# "fig": false# }

    4. How to convert List<Object> to JSON on playframework Java

      Thank you . You can prevent escaping by using in template. details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Html(Json.toJson(users))

    5. Testing for null JSON Objects in Java/Android

      capdragon Glad to help you ). will throw an exception if it receives null. details

      Reactions - Positive 5, Negative 15, Others 0

      1. String str = jObject.getString("AverageRating")
      2. float number = 0.f
      3. try{ number = Float.parseFloat(str)
      4. }catch (NumberFormatException e){ number = 0
      5. }

      Positive Reactions
      1. But, it still may be checked infrequent enough that performance costs of exception handling may be negligible/tolerable.
      2. good.
      3. ... and although purist is a fine description, I used the word religious because when you introduce a subjective concept like exceptional*, you are creating a rule that can't be proven or disproven (like my God* vs. your God*).
      4. @JeffreyBlattman, I totally agree that checking against null is a good/better solution.
      5. @Nate yes, that's why i said in the answer that i wrote that this only applies if receiving a null value is exceptional.
      Negative Reactions
      1. 1. don't use exceptions to process non-exceptional conditions 2. don't catch the base class Exception.
      2. @JeffreyBlattman, this is just a religious objection.
      3. I'm sorry I didn't thought of that a bit before.
      4. Preferring to reserve exception handling for less frequent error handling is fine ... making absolutist statements is almost never (!)
      5. Exceptions are used for signaling erroneous (exceptional) conditions which occur during the run time processing.".
      6. Depending on the actual application, the performance cost of catching an exception may very well be negligible.
      7. It now occurs to me; there could be 0 rows and yet the average could be 0. null as a return value clearly is an exception and should be handled appropriatelly.
      8. don't take my word for it ... "Exception are such anomalous conditions (or typically an event) which changes the normal flow of execution of a program.
      9. Exceptions can be a very useful language feature.
      10. this is just a guideline, and you are often forced to violate this by poor API design.
      11. Propagating general rules about not using exceptions is throwing the baby out with the bathwater.
      12. exceptions are for exceptional conditions ... things you don't expect to happen during normal operation of the code.
      13. I can guarantee people will read your comment above and take it as a general statement, and as such, I think it's poor advice.
      14. that being said, that use of exceptions in many APIs does not conform to that definition so i understand where folks get confused.
      15. He/she merely acknowledged that it's a case that must be handled.
      Other Reactions
      1. it's a design issue.
      2. There is no universal definition of what constitutes exceptional*.
      3. If the row will be empty 1 in 1000 times, that's not all the time, and it's not unexpected.
      4. in this case, the entity generating the JSON should either add a number (not a string, not a null object), or leave the field blank if the field is optional.
      5. What I would disagree with is absolutist statements, which you made in your comment above, and in your answer ("... in the field at all times.").
      6. Furthermore, the poster did not give us the information to determine whether having 0 rows is an exceptional condition or not.
      7. I guess you're right.
      8. But, I don't understand 1.
      9. in a nutshell, exceptional means unexpected.
      10. All right, I agree with 2.
      11. the definition of exceptional in the Java language is not subjective.
      12. i wouldn't call it religious, i'd call it purist.
      13. That sounds reasonable.
      14. Why?

    6. Javascript to Java using JSON

      json2.js takes care of adding the functions conditionally. To submit the data do This also assumes the server is responding with JSON. details

      Reactions - Positive 2, Negative 0, Others 0

      1. $.ajax({ type: 'post', data: JSON.stringify(data), contentType: 'application/json', dataType: 'json'})

      Positive Reactions
      1. True, but it also adds overhead, and requires set up.
      2. SSL is well- understood, and there are plenty of setup guides.
      Other Reactions
      1. I am guessing that by "securely" the OP meant "safe" when it comes to data integrity rather than safe against eavesdropping.
      2. @Null, SSL provides both.
      3. A custom digest solution is going to add both those too.

  79. Get element name with GSON

    I mean you could write a method that returns you a List of your relevant class. Something along the lines of . .. details

    1. Type type = new TypeToken<List<MyClass>>() {}.getType()
    2. List<MyClass> myObjects = getMyObjects(new JsonParser().parse(json).getAsJsonObject().get("foos"), type)
    3. public static List<T> getMyObjects(String jsonString, Type type) { Gson gson = new Gson()
    4. List<T> myList = gson.fromJson(jsonString, type)
    5. return myList
    6. }

    Positive Reactions
    1. I can, but I'd like to extract the key name first.
    Negative Reactions
    1. And after that you could use myObjectMap.get("foo") and retrieve the list of MyClass objects against it.
    Other Reactions
    1. When you say "key", the only thing that comes to mind is a HashMap.
    2. You use a string key such as "foo" or "bar" and retrieve the list of objects against it, something like Map> myObjectMap new HashMap>.

  80. Polymorphism with gson

    None .. details

    1. class InheritanceAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T>{.... public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context).... public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException....}

  81. Gson Expected BEGIN_ARRAY but was STRING

    None .. details

    1. import com.google.gson.Gson
    2. import java.io.FileReader
    3. import java.util.List
    4. public class App {
    5. public static void main(String[] args) throws Exception {
    6. Evento evento = new Gson().fromJson(new FileReader("input.json"), EventoWrapper.class).evento
    7. System.out.println(evento.descricao)
    8. }
    9. }
    10. class EventoWrapper {
    11. Evento evento
    12. }
    13. class Evento {
    14. String descricao
    15. String finalizado
    16. int id
    17. String localEvento
    18. String nome
    19. List<Convidado> convidados
    20. }
    21. class Convidado {
    22. String acompanhante
    23. int id
    24. String localHospedagem
    25. String nome
    26. String nomeCracha
    27. String observacoes
    28. String participante
    29. String publico
    30. }

  82. GSON GraphAdapterBuilder fails with interfaces

    It's too late in Italy to make it nicer. You need a delegate function like this a TypeAdapterFactory like this a pair of tests like these and some sample classes to verify that the tests pass While this has been a quick&dirty hack it works like a charme. .. details

    1. public final class InterfaceAdapterFactoryTest extends TestCase {
    2. public void testInterfaceSerialization1() {
    3. SampleInterface first = new SampleImplementation1(10)
    4. SampleInterfaceContainer toSerialize = new SampleInterfaceContainer("container", first)
    5. GsonBuilder gsonBuilder = new GsonBuilder()
    6. new GraphAdapterBuilder()
    7. .addType(SampleInterfaceContainer.class)
    8. .addType(SampleImplementation1.class)
    9. .addType(SampleImplementation2.class)
    10. .registerOn(gsonBuilder)
    11. gsonBuilder.registerTypeAdapterFactory(
    12. new InterfaceAdapterFactory(
    13. SampleInterface.class,
    14. new Class<?>[] {SampleImplementation1.class, SampleImplementation2.class}))
    15. Gson gson = gsonBuilder.create()
    16. String json = gson.toJson(toSerialize)
    17. System.out.println(json)
    18. SampleInterfaceContainer deserialized = gson.fromJson(json, SampleInterfaceContainer.class)
    19. assertNotNull(deserialized)
    20. assertEquals(toSerialize.getName(), deserialized.getName())
    21. assertEquals(toSerialize.getContent().getNumber(), deserialized.getContent().getNumber())
    22. }
    23. public void testInterfaceSerialization2() {
    24. SampleImplementation2 first = new SampleImplementation2(5, "test")
    25. SampleInterfaceContainer toSerialize = new SampleInterfaceContainer("container", first)
    26. first.Container = toSerialize
    27. GsonBuilder gsonBuilder = new GsonBuilder()
    28. new GraphAdapterBuilder()
    29. .addType(SampleInterfaceContainer.class)
    30. .addType(SampleImplementation1.class)
    31. .addType(SampleImplementation2.class)
    32. .registerOn(gsonBuilder)
    33. gsonBuilder.registerTypeAdapterFactory(
    34. new InterfaceAdapterFactory(
    35. SampleInterface.class,
    36. new Class<?>[] {SampleImplementation1.class, SampleImplementation2.class}))
    37. Gson gson = gsonBuilder.create()
    38. String json = gson.toJson(toSerialize)
    39. System.out.println(json)
    40. SampleInterfaceContainer deserialized = gson.fromJson(json, SampleInterfaceContainer.class)
    41. assertNotNull(deserialized)
    42. assertEquals(toSerialize.getName(), deserialized.getName())
    43. assertEquals(5, deserialized.getContent().getNumber())
    44. assertEquals("test", ((SampleImplementation2) deserialized.getContent()).getName())
    45. assertSame(deserialized, ((SampleImplementation2) deserialized.getContent()).Container)
    46. }
    47. }

  83. get key names from JSON object using Gson

    Of course I cannot currently think of any reason why such a thing could be useful. input_without_lists.json input_with_lists.json . .. details

    1. import com.google.gson.Gson
    2. import java.io.FileReader
    3. import java.util.ArrayList
    4. import java.util.Collection
    5. import java.util.List
    6. import java.util.Map
    7. public class App {
    8. public static void main(String[] args) throws Exception {
    9. List keys1 = getKeysFromJson("input_without_lists.json")
    10. System.out.println(keys1.size())
    11. System.out.println(keys1)
    12. List keys2 = getKeysFromJson("input_with_lists.json")
    13. System.out.println(keys2.size())
    14. System.out.println(keys2)
    15. }
    16. static List getKeysFromJson(String fileName) throws Exception {
    17. Object things = new Gson().fromJson(new FileReader(fileName), Object.class)
    18. List keys = new ArrayList()
    19. collectAllTheKeys(keys, things)
    20. return keys
    21. }
    22. static void collectAllTheKeys(List keys, Object o) {
    23. Collection values = null
    24. if (o instanceof Map) {
    25. Map map = (Map) o
    26. keys.addAll(map.keySet())
    27. // collect keys at current level in hierarchy values = map.values()
    28. } else if (o instanceof Collection) values = (Collection) o
    29. else // nothing further to collect keys from return
    30. for (Object value : values) collectAllTheKeys(keys, value)
    31. }
    32. }

    Positive Reactions
    1. Thanks!
    2. What I'm trying to do is parse a JSON object and place the values of each key in an array for later use.
    Other Reactions
    1. All the examples I've found show how to pull data from a key, but you need the key ahead of time.
    2. After I have each key I want to output them and then let the user tell me which data they want.
    3. I'll give that a try now.

  84. Gson json unable to get the result

    None .. details

    1. import static org.junit.Assert.assertEquals
    2. import com.google.gson.Gson
    3. import com.google.gson.annotations.SerializedName
    4. import java.util.List
    5. import org.junit.Test
    6. public class TestGson {
    7. private static final String NAME = "3mm nail"
    8. @Test
    9. public void testList() {
    10. final String json = "{\"result\":[{\"id\":21456,\"name\":\"" + NAME + "\",\"type\":\"2\" }]}"
    11. Gson gson = new Gson()
    12. ListWrapper wrapper = gson.fromJson(json, ListWrapper.class)
    13. assertEquals(NAME, wrapper.result.get(0).name)
    14. }
    15. static class ListWrapper {
    16. List<Result> result
    17. }
    18. static class ObjectWrapper {
    19. Result result
    20. }
    21. static class Result {
    22. @SerializedName("id")
    23. public int idItem
    24. @SerializedName("name")
    25. public String name
    26. }
    27. }

  85. Using Gson to parse subclasses with different fields

    None .. details

    1. package com.stackoverflow.q15578106
    2. import com.google.gson.Gson
    3. import com.google.gson.GsonBuilder
    4. import com.google.gson.JsonDeserializationContext
    5. import com.google.gson.JsonDeserializer
    6. import com.google.gson.JsonElement
    7. import com.google.gson.JsonObject
    8. import com.google.gson.JsonParseException
    9. import java.lang.reflect.Type
    10. import java.util.HashMap
    11. import java.util.List
    12. import java.util.Map
    13. public class Foo {
    14. public static void main(String[] args) {
    15. /* { "response": {"data": {"foo": "FOO"}}, "meta": {"errors": [], "success": 1} } */
    16. String input1 =
    17. "{\"response\": {\"data\": {\"foo\": \"FOO\"}},\"meta\": {\"errors\": [], \"success\": 1}}"
    18. /* { "response": {"data": {"bar": 42}}, "meta": {"errors": [], "success": 1} } */ String
    19. input2 =
    20. "{\"response\": {\"data\": {\"bar\": 42}},\"meta\": {\"errors\": [], \"success\": 1}}"
    21. processInput(input1)
    22. // {"response":{"data":{"foo":"FOO"}},"meta":{"errors":[],"success":1}} processInput(input2)
    23. // {"response":{"data":{"bar":42}},"meta":{"errors":[],"success":1}} } static void processInput(String jsonInput) { DataDeserializer dataDeserializer = new DataDeserializer()
    24. dataDeserializer.registerDataType("foo", A.class)
    25. dataDeserializer.registerDataType("bar", B.class)
    26. Gson gson = new GsonBuilder().registerTypeAdapter(Data.class, dataDeserializer).create()
    27. BaseResponse response = gson.fromJson(jsonInput, BaseResponse.class)
    28. System.out.println(new Gson().toJson(response))
    29. }
    30. }
    31. class DataDeserializer implements JsonDeserializer<Data> {
    32. Map<String, Class<? extends Data>> dataTypeRegistry =
    33. new HashMap<String, Class<? extends Data>>()
    34. void registerDataType(String jsonElementName, Class<? extends Data> javaType) {
    35. dataTypeRegistry.put(jsonElementName, javaType)
    36. }
    37. @Override
    38. public Data deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    39. throws JsonParseException {
    40. JsonObject jsonObject = json.getAsJsonObject()
    41. for (String elementName : dataTypeRegistry.keySet()) {
    42. if (jsonObject.has(elementName)) {
    43. Class<? extends Data> dataType = dataTypeRegistry.get(elementName)
    44. return context.deserialize(jsonObject, dataType)
    45. }
    46. }
    47. throw new RuntimeException("Oops")
    48. }
    49. }
    50. class BaseResponse {
    51. Response response
    52. Meta meta
    53. }
    54. class Meta {
    55. List<String> errors
    56. int success
    57. }
    58. class Response {
    59. Data data
    60. }
    61. class Data {}
    62. class A extends Data {
    63. String foo
    64. }
    65. class B extends Data {
    66. int bar
    67. }

    • See Also (1)
    1. Polymorphism with gson

      Following is one such example. . details

      Reactions - Positive 1, Negative 2, Others 0

      1. // output:// Starting machine1// Stopping machine2import java.lang.reflect.Type
      2. import com.google.gson.FieldNamingPolicy
      3. import com.google.gson.Gson
      4. import com.google.gson.GsonBuilder
      5. import com.google.gson.JsonDeserializationContext
      6. import com.google.gson.JsonDeserializer
      7. import com.google.gson.JsonElement
      8. import com.google.gson.JsonObject
      9. import com.google.gson.JsonParseException
      10. import java.util.HashMap
      11. import java.util.Map
      12. public
      13. class Foo { // [{"machine_name":"machine1","command":"start"},{"machine_name":"machine2","command":"stop"}] static String jsonInput = "[{\"machine_name\":\"machine1\",\"command\":\"start\"},{\"machine_name\":\"machine2\",\"command\":\"stop\"}]"
      14. public static void main(String[] args) {
      15. GsonBuilder gsonBuilder = new GsonBuilder()
      16. gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
      17. CommandDeserializer deserializer = new CommandDeserializer("command")
      18. deserializer.registerCommand("start", Start.class)
      19. deserializer.registerCommand("stop", Stop.class)
      20. gsonBuilder.registerTypeAdapter(Command.class, deserializer)
      21. Gson gson = gsonBuilder.create()
      22. Command[] commands = gson.fromJson(jsonInput, Command[].class)
      23. for (Command command : commands) {
      24. command.execute()
      25. }
      26. }
      27. }
      28. class CommandDeserializer implements JsonDeserializer<Command> {
      29. String commandElementName
      30. Gson gson
      31. Map<String, Class<? extends Command>> commandRegistry
      32. CommandDeserializer(String commandElementName) {
      33. this.commandElementName = commandElementName
      34. GsonBuilder gsonBuilder = new GsonBuilder()
      35. gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
      36. gson = gsonBuilder.create()
      37. commandRegistry = new HashMap<String, Class<? extends Command>>()
      38. }
      39. void registerCommand(String command, Class<? extends Command> commandInstanceClass) {
      40. commandRegistry.put(command, commandInstanceClass)
      41. }
      42. @Override
      43. public Command deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      44. throws JsonParseException {
      45. try {
      46. JsonObject commandObject = json.getAsJsonObject()
      47. JsonElement commandTypeElement = commandObject.get(commandElementName)
      48. Class<? extends Command> commandInstanceClass =
      49. commandRegistry.get(commandTypeElement.getAsString())
      50. Command command = gson.fromJson(json, commandInstanceClass)
      51. return command
      52. } catch (Exception e) {
      53. throw new RuntimeException(e)
      54. }
      55. }
      56. }
      57. abstract class Command {
      58. String machineName
      59. Command(String machineName) {
      60. this.machineName = machineName
      61. }
      62. abstract void execute()
      63. }
      64. class Stop extends Command {
      65. Stop(String machineName) {
      66. super(machineName)
      67. }
      68. void execute() {
      69. System.out.println("Stopping " + machineName)
      70. }
      71. }
      72. class Start extends Command {
      73. Start(String machineName) {
      74. super(machineName)
      75. }
      76. void execute() {
      77. System.out.println("Starting " + machineName)
      78. }
      79. }

      Positive Reactions
      1. If you can change APIs, then note that Jackson currently has a mechanism for relatively simple polymorphic deserialization.
      Negative Reactions
      1. [RuntimeTypeAdapter]( URL_http://code.google.com/p/google-gson/source/browse/trun k/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.
      2. java) is now complete, unfortunately it doesn't look like it's in Gson core yet.
      Other Reactions
      1. I posted some examples at URL_http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson - into.html.
      2. :-(.

  86. Sending Complex JSON Object

    None .. details

    1. try { JsonSerializer<Date> ser = new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext comtext) { return src == null ? null : new JsonPrimitive("/Date("+src.getTime()+"+05300)/")
    2. } }
    3. JsonDeserializer<Date> deser = new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext jsonContext) throws JsonParseException { String tmpDate = json.getAsString()
    4. Pattern pattern = Pattern.compile("\\d+")
    5. Matcher matcher = pattern.matcher(tmpDate)
    6. boolean found = false
    7. while (matcher.find() && !found) { found = true
    8. tmpDate = matcher.group()
    9. } return json == null ? null : new Date(Long.parseLong(tmpDate))
    10. } }

    • See Also (1)
    1. GSON Serialize boolean to 0 or 1

      I'd prefer not to rewrite my booleans as ints as that will cause several issues with existing code nonobvious hard to read hard to enforce etc. To make it correct way you can use something like that And then use it Hope this helps someone . details

      Reactions - Positive 1, Negative 0, Others 0

      1. import com.google.gson.JsonDeserializationContext
      2. import com.google.gson.JsonDeserializer
      3. import com.google.gson.JsonElement
      4. import com.google.gson.JsonParseException
      5. import com.google.gson.JsonPrimitive
      6. import com.google.gson.JsonSerializationContext
      7. import com.google.gson.JsonSerializer
      8. import java.lang.reflect.Type
      9. public class BooleanSerializer implements JsonSerializer<Boolean>, JsonDeserializer<Boolean> {
      10. @Override
      11. public JsonElement serialize(Boolean arg0, Type arg1, JsonSerializationContext arg2) {
      12. return new JsonPrimitive(arg0 ? 1 : 0)
      13. }
      14. @Override
      15. public Boolean deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
      16. throws JsonParseException {
      17. return arg0.getAsInt() == 1 ? true : false
      18. }
      19. }

      Positive Reactions
      1. Correct & Perfect Answer...

  87. Tweak JSON or GSON?

    You can't ignore the top-level object with single property. Massaging it to the below format works for me As the below demonstrates Giving the below resp . .. details

    1. public class TryMe {
    2. public static void main(String[] args) {
    3. Gson gson = new Gson()
    4. List<Widget> widgets = gson.fromJson(json, new TypeToken<List<Widget>>() {}.getType())
    5. System.out.println(widgets)
    6. }
    7. }
    8. class Widget {
    9. @SerializedName("id")
    10. private Long id
    11. @SerializedName("status")
    12. private String status
    13. @SerializedName("uuid")
    14. private String uuid
    15. public Long getId() {
    16. return id
    17. }
    18. public void setId(Long id) {
    19. this.id = id
    20. }
    21. public String getStatus() {
    22. return status
    23. }
    24. public void setStatus(String status) {
    25. this.status = status
    26. }
    27. public String getUuid() {
    28. return uuid
    29. }
    30. public void setUuid(String uuid) {
    31. this.uuid = uuid
    32. }
    33. @Override
    34. public String toString() {
    35. return "Widget [id=" + id + ", status=" + status + ", uuid=" + uuid + "]"
    36. }
    37. }

  88. How to convert a String to JsonObject using gson library

    What I unsuccesfully do . You can convert it to a JavaBean if you want using To use JsonObject which is more flexible use the following Which is equivalent to the following . .. details

    1. String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}"
    2. JsonParser jsonParser = new JsonParser()
    3. JsonObject jo = (JsonObject)jsonParser.parse(json)
    4. Assert.assertNotNull(jo)
    5. Assert.assertTrue(jo.get("Success").getAsString())

    • See Also (7)
    1. how to parse unquoted JSON string

      regards,Jan . You can use JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES with Jackson to allow unquoted field names . details

      Reactions - Positive 3, Negative 0, Others 0

      1. JsonFactory factory = new JsonFactory()
      2. factory.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
      3. JsonParser jp = factory.createJsonParser(new FileInputStream("content.json"))

      Positive Reactions
      1. But yes, it looks like I will have to write my own parser.
      2. I did use that but it will not help for the unquoted values or for unquoted numeric keys (e.g.
      3. In my case, I know that I will have only string without , as values.
      Other Reactions
      1. I'm guessing you will have to write your own deserializer.
      2. "0: myValue").
      3. For "licence":"one,two" malformed as licence:one,two how do you suggest choosing the interpretation?
      4. Jackson's ObjectMapper and Module functionality might help you.

    2. How can I read a value as JSON while using JsonParser.nextToken in Jackson

      What is the question. Why don't you just use to read the sub-tree when you are at it. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonParser.readValueAsTree()

    3. Android JSON Parser

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONParser()

    4. How to prevent Gson from converting a long number (a json string ) to scientific notation format?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson output: {numbers=[2.68627104E8, 4.85677888E8, 5.068848E8]} JsonParser output: {"numbers":[268627104,485677888,506884800]}

    5. GWT JSONObject to overlay types (or using JSONObject in shared)

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONParser.parseStrict()

    6. check if file is json, java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonParser#parse()

    7. A better Java JSON library?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. /** * Parse a generalized data structure from a JSON input stream. * <p> * All values are added using the <code>crtmbrcbk</code> callback. * <p> * <b><u>Reminder</b></u> * <p> * When using a reflected method, don't forget to configure your code obfuscator to retain it in unobfuscated form. * * @param psr The parser to use. * @param tgt Target object to which to add members
      2. if this is null a new object is created using the callback. * @param maxlvl Maximum level to recursively parse substructures, including arrays (objects at a deeper level are silently ignored). * @param crtmbrcbk A callback object invoked to create a member value. * @see #createMemberCallback(Object,String) */static public Object parseObject(JsonParser psr, Object tgt, int maxlvl, Callback crtmbrcbk) { return _parseObject(psr,tgt,maxlvl,crtmbrcbk,new Object[4],false)
      3. }static private Object _parseObject(JsonParser psr, Object tgt, int maxlvl, Callback crtmbrcbk, Object[] crtprm, boolean arr) { int evt
      4. // event code if(tgt==null) { tgt=crtmbrcbk.invoke(crtprm,psr,null,"",null)
      5. } while((evt=psr.next())!=JsonParser.EVT_INPUT_ENDED && evt!=JsonParser.EVT_OBJECT_ENDED && evt!=JsonParser.EVT_ARRAY_ENDED) { String nam=psr.getMemberName()
      6. switch(evt) { case JsonParser.EVT_OBJECT_BEGIN : { if(nam.length()>0) { if(maxlvl>1) { _parseObject(psr,crtmbrcbk.invoke(crtprm,psr,tgt,nam,null),(maxlvl-1),crtmbrcbk,crtprm,false)
      7. } else { psr.skipObject()
      8. } } else { _parseObject(psr,tgt,maxlvl,crtmbrcbk,crtprm,false)
      9. } } break
      10. case JsonParser.EVT_ARRAY_BEGIN : { if(!arr) { _parseObject(psr,tgt,maxlvl,crtmbrcbk,crtprm,true)
      11. // first level of any array is added directly to the inherently list-supporting object } else { if(maxlvl>1) { _parseObject(psr,crtmbrcbk.invoke(crtprm,psr,tgt,nam,null),(maxlvl-1),crtmbrcbk,crtprm,true)
      12. } else { psr.skipArray()
      13. } } } break
      14. case JsonParser.EVT_OBJECT_MEMBER : { crtmbrcbk.invoke(crtprm,psr,tgt,nam,psr.getMemberValue())
      15. } break
      16. } } return tgt
      17. }

  89. Sending list in JSON request

    None .. details

    1. $.ajax({ url : 'testURL.do', type : 'post', data : data, cache : false, dataType : 'json', success : function (jsonResponse) { var jsonValue = $.parseJSON(jsonResponse.paramName)
    2. }, error : function (error) {}})

  90. Difficulty Parsing JSON with JQuery

    You don't need to use each here. . .. details

    1. $(document).ready(function () { $.getJSON('SearchServlet', function(tweet) { var table = $('#resultsTable')
    2. $('<tr>').appendTo(table) .append($('<td>').text(tweet.username)) .append($('<td>').text(tweet.status)) .append($('<td>').text(tweet.date)) .append($('<td>').text(tweet.retweets))
    3. })
    4. })

    Positive Reactions
    1. I also added a console.log("test") after the $.getJSON call but as you can see in the console, it's not logged there and I'm not entirely sure why since it appears the function is, at the very least, calling the doGet on the servlet fine.
    2. Thanks for the help, it's much appreciated.
    3. If I log "test" to the console [after]( URL_http://i.imgur.com/skzBgcY.png ) and outside the $.getJSON() it also works fine so it appears there's some issue between the $.getJSON() call and what happens immediately afterward.
    4. I put console.log("test") in [after]( URL_http://i.imgur.com/ql0HhaT.png ) .ready() is called and it logs to the console fine.
    5. Thank you very much Alexander, it's much appreciated.
    6. Firebug is showing it GETing the data fine, an example being searching for the term "Twitter" resulted in:.
    7. It works perfectly!
    8. Thanks again Alexander.
    Negative Reactions
    1. @richardb, I can see from the third screenshot that the JSON response has an invalid format.
    Other Reactions
    1. Even with console.log(tweet) included in the code?
    2. Done.
    3. Hi Alexander, I've taken a few screenshots of the console with the results for "Alexander" [first]( URL_http://i.imgur.com/kX6EdKt.png) , [headers]( URL_http://i.imgur.com/hlJoLuq.png ) and [full response objects]( URL_http://i.imgur.com/yFp9hCO.png ) .
    4. I updated the answer.
    5. Firebug console displays the GET response JSON objects, but the dev console on Chrome is showing nothing?
    6. If I move it to [within]( URL_http://i.imgur.com/bWO4rhh.png ) the $.getJSON() is called it doesn't log to the console.
    7. Neither are rendering the table though or even the tags that it should be.
    8. You need to add all the tweetResult in a list and serialize the list instead.
    9. Just to follow up on that.
    10. Can you show us the response as Firebug or Chrome Developer Tools is displaying it?
    11. Is tweet being populated?
    12. @richardb, with that fix your original code should work.
    13. Hi Alexander, I tried out the code you provided and it's still not rendering the table.
    14. @richardb, just to be clear.

    • See Also (6)
    1. Parsing JSONObject in javascript or Jquery

      Thanks. Additionally you could in Java respond with the Content-Type application/json and then in the jQuery AJAX you will receive the JSON already parsed for you. details

      Reactions - Positive 0, Negative 0, Others 0

      1. var json = $.parseJSON( jsonString )
      2. // This one wouldn't be supported in old browsersjson = JSON.parse( jsonString )

    2. Parsing external JSON file(containing array elements) in Javascript using JQuery

      day is undefined you probably meant day'. day is undefined you probably meant day' though what you really want is Just iterate over the day array populating your two child arrays. details

      Reactions - Positive 1, Negative 0, Others 0

      1. $.getJSON('TotalUsers.json', function(data) { var valuesTotal = []
      2. var daysTotal = []
      3. $.each(data.day, function(key, obj) { valuesTotal.push('<li id="value-' + key + '">' + obj["@value"] + '</li>')
      4. daysTotal.push('<li id="day-' + key + '">' + obj["@date"] + '</li>')
      5. })
      6. })

      Positive Reactions
      1. thanks a lot.
      Other Reactions
      1. It helped.

    3. Java: Parsing more than one Json Object in a string

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. $counter = 0
      2. // read them back$result = mysql_query( "SELECT * FROM locations" )
      3. echo '['
      4. while( $data = mysql_fetch_assoc($result) ) {if (&counter >= 1){ echo ','
      5. }$latFromDb = $data['latitude']
      6. $longFromDb = $data['longitude']
      7. $variable = array( 'lon'.$counter => "$longFromDb", 'lat'.$counter => "$latFromDb" )
      8. // One JSON for both variablesecho json_encode($variable)
      9. $counter++
      10. }echo ']'

    4. Parsing JSON array with a sub-array with GSON?

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new Gson()
      2. AccessorClass object = gson.fromJson(result, AccessorClass.class)

    5. Parsing non-standard JSON

      For JSON format questions go here It's not totally clear where you want to do this conversion to JSON but in Javascript you can use window.JSON.stringify to convert it to JSON. Demo . details

      Reactions - Positive 1, Negative 0, Others 0

      1. var object = { names: { en: 'VirtualMarket-2MinuteLevel', es: 'VirtualMarket-2MinuteLevel' }, status: 'A', displayed: 'Y', start_time: '2010-11-2600: 00: 00', start_time_xls: { en: '26thofNov201000: 00am', es: '26Nov201000: 00am' }, suspend_at: '2010-11-2619: 57: 59', is_off: 'Y', score_home: '', score_away: '', bids_status: '', period_id: '', curr_period_start_time: '', score_extra_info: '', ev_id: 2257335, blurb: '', last_mkts_of_day: false, follow_hcap_mkt: 10999896 }, json = window.JSON.stringify( object )

      Positive Reactions
      1. @minitech Good point.
      Other Reactions
      1. Any solution?
      2. Edited.
      3. Maybe this would be better off as a comment.

    6. Parsing JSON Object Array

      Thank You all I was able to figure it out my Problem. You need to set the dataType option to the type of data you're expecting back from the server . details

      Reactions - Positive 0, Negative 1, Others 0

      1. $.ajax({ dataType: 'json', url: 'getFolders', type: 'POST', data: 'uniqueID=' + uniqueID , //console.log(data)
      2. success: function(result) { //parse result alert("JSON result "+ result[0].uniqueId)
      3. }//end success })

      Negative Reactions
      1. IMO it's a bug (at a minimum it's inconsistent with how it acknowledges content types of "application/xml" or "text/html").
      Other Reactions
      1. Yes, jQuery ignores the "application/json" Content type in the response for some reason, so you need to specify dataType.
      2. Woops, that last example was supposed to read "text/xml".

  91. Deserializing JSON data using Gson

    But this should give an idea. . .. details

    1. public class GeometryDeserializer implements JsonDeserializer<Geometry> {
    2. @Overridepublic
    3. Geometry deserialize(JsonElement json, Type typeofT, JsonDeserializationContext context)
    4. throws JsonParseException {
    5. String type = json.getAsJsonObject().get("type").toString()
    6. JsonArray coordinates = json.getAsJsonObject().getAsJsonArray("coordinates")
    7. GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null)
    8. Coordinate coord =
    9. new Coordinate(coordinates.get(0).getAsDouble(), coordinates.get(1).getAsDouble())
    10. Geometry point = geometryFactory.createPoint(coord)
    11. return point
    12. }
    13. }

  92. parse a JSON feed using GSON and get an array instead of multi params

    Otherwise you would need to define a Result object to use instead of that Map that had all the possible method types as fields and use the SerializedName annotation because of the non-legal Java names Option C if you really want a List is creating your own custom deserializer that is passed the parsed JSON and create an object that had a List in it instead of a Map or POJO. Untested but should work To use it you register it with . .. details

    1. class MyResponse {
    2. public int status
    3. public List<APIMethod> methods
    4. public MyResponse(int status, List<APIMethod> methods) {
    5. this.status = status
    6. this.methods = methods
    7. }
    8. }
    9. class MyDeserializer implements JsonDeserializer<MyResponse> {
    10. public MyResponse deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
    11. throws JsonParseException {
    12. Gson g = new Gson()
    13. List<APIMethod> list = new ArrayList<APIMethod>()
    14. JsonObject jo = je.getAsJsonObject()
    15. Set<Entry<String, JsonElement>> entrySet = jo.getAsJsonObject("result").entrySet()
    16. for (Entry<String, JsonElement> e : entrySet) {
    17. APIMethod m = g.fromJson(e.getValue(), APIMethod.class)
    18. list.add(m)
    19. }
    20. return new MyResponse(jo.getAsJsonPrimitive("status").getAsInt(), list)
    21. }
    22. }

  93. Pass json object to a play-framework action

    Try with this ajax post . To cast the entire input body into a Model class Also the above code takes the resulting Model object and serializes it back out to JSON as the response body. .. details

    1. public static void create(JsonObject body) { CaseFolder caseFolder = new Gson().fromJson(body, CaseFolder.class)
    2. caseFolder.user = getConnectedUser()
    3. if(caseFolder.validateAndSave()) { renderJSON( new JSONSerializer() .exclude("*.class") .exclude("user") .serialize(caseFolder))
    4. } else error()
    5. }

  94. JSON parsing using Gson for java

    The integer string values can be mapped as is. Json can be parsed like this Here is an example http-get-solr-request-and.html url-encode-http-get-solr-request-and.html . .. details

    1. Gson gson = new GsonBuilder().create()
    2. Response r = gson.fromJson(jsonString, Response.class)

    • See Also (1)
    1. Parsing Json Feeds with google Gson

      The integer string values can be mapped as is. Json can be parsed like this Here is an example http-get-solr-request-and.html url-encode-http-get-solr-request-and.html . details

      Reactions - Positive 0, Negative 0, Others 0

      1. Gson gson = new GsonBuilder().create()
      2. Response r = gson.fromJson(jsonString, Response.class)

  95. Struts2 How to Return a JSON Response

    In Action class put below code. In JSP put below code This will print JSON data if you want to manipulate JSON data you cat the data in var s:set tag and access the variable in entire page. .. details

    1. public class Struts2Action extends ActionSupport {
    2. public String jsonString = ""
    3. public String execute() {
    4. Gson gson = new Gson()
    5. jsonString = gson.toJson(audioTaggingService.findTagsByName(q))
    6. System.out.println(jsonString)
    7. return "success"
    8. }
    9. }

    Other Reactions
    1. Let me know if you are looking for other thing.
    2. If the OP is looking for a JSON response, it's more likely they don't want HTML, need the content type set, etc.
    3. Agree with Dave.

  96. Serialize form inputs to JSON using Backbone.js

    None .. details

    1. getStatus: function(event){ var data = JSON.stringify($('form').serializeObject())
    2. this.model.set(data)
    3. }

    • See Also (5)
    1. Spring 3.1, JSON response ModelAndView

      True it will return a String if an object is needed replace String with your object and you can serialize it using jackson library for example. And controller returning ModelAndView. details

      Reactions - Positive 0, Negative 0, Others 0

      1. $("#menuUrl").submit(function(){ var obj = $(this).serializeObject()
      2. obj.parentId = getParentId(menuDivId)
      3. $.ajax({ url: config.resourcePath+"/addUrl.html", data : JSON.stringify(obj), contentType : 'application/json', type : 'POST', context: document.body, }).done(function(response) { $("#site").append(response)
      4. })
      5. return false
      6. })

    2. Sending a consistent JSON response to report exceptions with Sitebricks

      Not exactly answering your question but what I did to manage errors is the following. In the parent class of all my REST endpoints i've declared the following method Then in all my endpoints I'm catching exceptions and use this method to reply a generic error. details

      Reactions - Positive 0, Negative 0, Others 0

      1. protected Reply<?> error(String errorCode) { logger.error(errorCode)
      2. return Reply.with(new ErrorJSONReply(errorCode)).as(Json.class).headers(headers()).type("application/json
      3. charset=utf-8")
      4. }

    3. Spring 3.0 making JSON response using jackson message converter

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. $.ajax({ type: "post", url: "sync", //your valid url contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me) data: JSON.stringify(jsonobject), //json object or array of json objects success: function(result) { //do nothing }, error: function(){ alert('failure')
      2. }})

    4. How to parse a dynamic JSON key in a Nested JSON result

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package so7304002
      2. import java.util.List
      3. import java.util.Map
      4. import lombok.AccessLevel
      5. import lombok.Data
      6. import lombok.NoArgsConstructor
      7. import com.google.gson.Gson
      8. import com.google.gson.annotations.SerializedName
      9. import com.google.gson.reflect.TypeToken
      10. @NoArgsConstructor(access = AccessLevel.PRIVATE)public final class JsonDemo { @Data private static class MyMap { private int count
      11. @SerializedName("more_description") private String moreDescription
      12. private int seq
      13. } @Data private static class Product { private String product
      14. private int id
      15. @SerializedName("question_mark") private Map<String, MyMap> questionMark
      16. } @Data private static class MyObject { private String status
      17. @SerializedName("search_result") private List<Product> searchResult
      18. } private static final String INPUT = ""
      19. // your JSON public static void main(final String[] arg) { final MyObject fromJson = new Gson().fromJson(INPUT, new TypeToken<MyObject>(){}.getType())
      20. final List<Product> searchResult = fromJson.getSearchResult()
      21. for (final Product p : searchResult) { System.out.println("product: " + p.getProduct() + "\n" + p.getQuestionMark()+ "\n")
      22. } }}

    5. Getting JSONObject from String

      You can use CODESNIPPET_JAVA8 to gather all form fields as parameters. Here's a kickoff example of how the JSP should look like And here is how the servlet which listens on an url-pattern of register can look like With the jQuery-form plugin it'll be more transparent. details

      Reactions - Positive 0, Negative 0, Others 0

      1. <!DOCTYPE html><html lang="en"> <head> <title>Test</title> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function() { $('#form').submit(function() { $form = $(this)
      2. $.post($form.attr('action'), $form.serialize(), function(response) { alert(response)
      3. // "OK" })
      4. return false
      5. })
      6. })
      7. </script> </head> <body> <form id="form" action="register" method="post"> <input type="text" name="username"> <input type="password" name="password"> <input type="submit"> </form> </body></html>

  97. Json as parameter to Grails controller

    I can recommend you JSON-3-library . At this case it going to be 2. .. details

    1. $.ajax({ type: "POST", data: JSON.stringify(matrixArray), url: "/turingpages/factorize/create", success: function(data) { //USE DATA } })

    Other Reactions
    1. When I use stringify, my request.JSON is an empty object: [15:52:12.302] {"array":[[1,2,3],[3,4,5],[5,6,7]]} @ URL_http://localhost:8080/turingpages/js/dataFeed.js:15[15:52:12.499 ] POST URL_http://localhost:8080/turingpages/factorize/create [HTTP/1.1 200 OK 18ms][15:52:12.528] {} @ URL_http://localhost:8080/turingpages/js/dataFeed.js:22 .
    2. The above log is a printout of the array before the request and a printout of the return.
    3. In the grails controller, I am simply returning request.JSON.
    4. Try to add contentType: 'application/json' and dataType: 'json' options.

    • See Also (1)
    1. Why is my jquery ajax giving a 406

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. $.ajax({type:'GET',url: '/ratings/' + ID + '?rating=' + rating,dataType: 'json',success: function(data){ var ratingResult = data.ratingResult
      2. //or sometimes you have to do data[0] var ratingresult = data[0].ratingResult
      3. })

  98. Out of memory error while parsing a large JSON using Jackson library on Android

    If so either need to use ObjectMapper.readValues or raw Streaming API JsonParser for iteration then readValueAs when located at root of sub-time. We use here the gson lib and with the code above we can get files larger than 50Mb without problem Try this lib that's a good one with the jackson we use only in the server side because jackson is more slow in the Android than gson at least in our test. .. details

    1. public static <T extends Object> T readFile(String caminho_arquivo, Type type) { GsonBuilder gson_builder = new GsonBuilder()
    2. final SimpleDateFormat sdf_date = new SimpleDateFormat("yyyy-MM-dd")
    3. final SimpleDateFormat sdf_datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
    4. gson_builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>(){ @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { if (json.getAsJsonPrimitive().getAsString().length() == 10) return sdf_date.parse(json.getAsJsonPrimitive().getAsString())
    5. else return sdf_datetime.parse(json.getAsJsonPrimitive().getAsString())
    6. } catch (ParseException e) { Log.e("JSON", "Erro na deserializao de datas no JSON: " + json.getAsJsonPrimitive().getAsString())
    7. return null
    8. } } })
    9. Gson gson = gson_builder.create()
    10. File fileJSON = new File(caminho_arquivo)
    11. FileReader reader = null
    12. try { reader = new FileReader(fileJSON)
    13. return gson.fromJson(reader, type)
    14. } catch (FileNotFoundException e) { e.printStackTrace()
    15. } finally { try { reader.close()
    16. if (fileJSON.exists()) fileJSON.delete()
    17. } catch (IOException e) { e.printStackTrace()
    18. } } return null
    19. }

    Positive Reactions
    1. Well, it's not buggy, it's working very well for me, I had special characters without problem.
    2. And with Jackson don't help me when I need to parse large files, so for my app GSON was the best, even more slow, can read large files.
    3. As to Gson vs Jackson: just note that code you gave is different from original one -- you are using POJOs (which makes sense!
    4. Also, links to performance test would be great -- the only commonly cited one ( URL_http://www.martinadamek.com/2011/02/04/json-parsers-performance-on-android - with-warmup-and-multiple-iterations/) does not show Gson as faster.
    Negative Reactions
    1. This is a common mistake made by Java developers, so perhaps you just cut'n pasted it from somewhere.
    2. Gson does have faster startup time, however; and version 2.1 is ok (earlier versions were very slow).
    3. Was not meant as an insult, although wording may have been strong.
    4. Above code is buggy -- does not specify character encoding to use for FileReader, so will probably barf on non-ASCII input.
    5. It may work on your platform; but it can easily fail on others; hence it is broken.
    Other Reactions
    1. It may be easily changed to do that, and Jackson approach will likewise work.
    2. ), but Jackson code referred did not.
    3. The "caminho_arquivo" is the location of the file in the SDCard.
    4. But there should be no need to construct a Reader, just pass in InputStream.
    5. You should just specify the encoding (UTF-8).
    6. So this is not a real difference between two approaches.
    7. I use that because I get a zipped file from the server, after that I unzip the file and get the .json file...

    • See Also (1)
    1. GSON throws exception parsing empty Date field

      the JSon generating part but know the format as it should be when not empty you should just write an own deserializer that can handle empty values like e.g. See Serialization-and-Deserializ guide#TOC-Custom-Serialization-and-Deserializ . details

      Reactions - Positive 0, Negative 0, Others 0

      1. GsonBuilder gsonBuilder = new GsonBuilder()
      2. gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm")
      3. @Override public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { try { return df.parse(json.getAsString())
      4. } catch (ParseException e) { return null
      5. } } })
      6. Gson gson = gsonBuilder.create()

  99. Deserializing a Map&lt;String, Object&gt; field with Gson

    It's very strange it stays to null for me. For me this code Prints this However keep in mind that I have stripped the wrapping json object in the file I parse. .. details

    1. public class Main { public static void main(String[] args) throws IOException { GsonBuilder builder = new GsonBuilder()
    2. builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    3. Gson gson = builder.create()
    4. FileInputStream inputStream = new FileInputStream(new File("bobi.json"))
    5. InputStreamReader reader = new InputStreamReader(inputStream)
    6. User user = gson.fromJson(reader, User.class)
    7. System.out.println(user.getName())
    8. System.out.println(user.getId())
    9. for (String property : user.getProperties().keySet()) { System.out.println("Key: " + property + " value: " + user.getProperties().get(property))
    10. } reader.close()
    11. }

    Positive Reactions
    1. Thanks for your help!.
    2. So I switch the naming policy to IDENTITY and now it works!.
    3. I have accepted the answer but I can't upvote.
    4. If I helped you accept and upvote my answer - this is how SO is meant to work.
    5. Thanks for your help.
    6. Have a nice day!.
    Negative Reactions
    1. Sorry.
    2. In fact, it's my fault.
    3. Ok I found my mistake.
    4. It was the FieldNamingPolicy the problem.
    5. I have not enough reputations.
    6. @FranckYapadesouciAnso: Btw identity is the default field naming policy, you do not need to specify it.
    Other Reactions
    1. @FranckYapadesouciAnso: How did it affect the parsing?
    2. I try your code but properties is always null...
    3. @FranckYapadesouciAnso: Added.
    4. Also, I can see you are new around here.
    5. I'm on JDK7 and Gson 2.2.2 if I can help...
    6. Gson 2.1, java 1.7.
    7. The field naming policy set on LOWER_CASE_WITH_UNDERSCORES try to search dyn_prop in the json and not dynProp.
    8. For the topic I simplified field name.
    9. Could you post the user object that you used?
    10. The propertyfield in the topic is dynProp in my code.

  100. let Gson throw exceptions on wrong types

    None .. details

    1. This is foothis is barThis is foonullException in thread "main" com.google.gson.JsonParseException: Missing field in JSON: foo

  101. JSON to Java: How to model lists of objects into generic object class whose object name from json is variable

    None .. details

    1. import com.google.gson.Gson
    2. import com.google.gson.GsonBuilder
    3. import com.google.gson.reflect.TypeToken
    4. import java.lang.reflect.Type
    5. import java.util.List
    6. import java.util.logging.Level
    7. import java.util.logging.Logger
    8. public class GsonExample {
    9. private static final Logger logger = Logger.getLogger(GsonExample.class.getName())
    10. private static final String JSON =
    11. "{"
    12. + "\"2002\": ["
    13. + "{"
    14. + "\"d\": \"description\","
    15. + "\"t\": \"title\""
    16. + "}"
    17. + "],"
    18. + "\"2003\": ["
    19. + "{"
    20. + "\"d\": \"description\","
    21. + "\"t\": \"title\""
    22. + "}"
    23. + "]"
    24. + "}"
    25. public static void main(String[] args) {
    26. GsonExample e = new GsonExample()
    27. e.run()
    28. }
    29. private void run() {
    30. GsonBuilder builder = new GsonBuilder()
    31. Type type = new TypeToken<List<Program>>() {}.getType()
    32. builder.registerTypeAdapter(type, new ProgramsDeserializer())
    33. Gson gson = builder.create()
    34. List<Program> programs = gson.fromJson(JSON, type)
    35. logger.log(Level.INFO, "{0}", programs)
    36. }
    37. }

  102. JSON array in GSON parses, but objects are empty

    None .. details

    1. class AnswerDeserializer implements JsonDeserializer<Answer> {
    2. public Answer deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
    3. throws JsonParseException {
    4. return new Answer(
    5. je.getAsJsonObject().get("answer").getAsJsonObject().get("text").getAsString())
    6. }
    7. }

    • See Also (1)
    1. Converting json string of Intent to object of Intent giving exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. public class UriDeserializer implements JsonDeserializer<Uri> {
      2. @Override
      3. public Uri deserialize(
      4. final JsonElement src, final Type srcType, final JsonDeserializationContext context)
      5. throws JsonParseException {
      6. return Uri.parse(src.getAsString())
      7. }
      8. }

  103. how can we have implicit in json

    Eg XML JSON I want the desired output of JSON in the following format . According to root "Write-to-JSON-with-the-self-contained-JSON-driver-dropping-the-root in-the-JSON-tutorial you can write something like this . .. details

    1. XStream xstream = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer writer) { return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE)
    2. }})

    Positive Reactions
    1. @ruack hey thanks buddy.But the object of Class A what i Have mentioned is not the root element.It is has a reference inside class C which supposed to be the root class.
    Negative Reactions
    1. @user1065080: For that, I guess you need to use JettisonMappedXmlDriver (which serializes to XML and then translates to JSON; see [its Javadoc](http:/ /xstream.codehaus.org/javadoc/com/thoughtworks/xstream/io/json/JettisonMappedX mlDriver.html)) instead of JsonHierarchicalStreamDriver.
    Other Reactions
    1. class B { @XstreamAlias("fruit") private A a: }.
    2. And do we have any annotations similar to xstreamImplicit which will do the needfull of dropping the tag or key : for json.

    • See Also (2)
    1. XStream parse JSON with no root node

      always prepend root but then configure it as alias to your class in XStream instance so I don't think this is any cleaner than 1 . Use the below code . details

      Reactions - Positive 0, Negative 0, Others 0

      1. XStream xstream = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer writer) { return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE)
      2. } })

      Other Reactions
      1. What about reading JSON without a root node; is there sample code you can provide that?

    2. How to disable pretty-printing(white space/newline) in XStream?

      For XML you have to change the way how you serialize The line changed to line For JSON you only change the way how the XStream is created. So the initialization of the XStream is changed to Note that the 4-parameter JsonWriter constructor is used. details

      Reactions - Positive 1, Negative 0, Others 0

      1. private final XStream xstreamOut = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer writer) { return new JsonWriter(writer, new char[0], "", JsonWriter.DROP_ROOT_MODE)
      2. }})

      Positive Reactions
      1. pretty-Print Writer does not suffice my needs.
      Other Reactions
      1. I was using new Writer().write method to add prolog and stylesheets, but CompactWriter does not have this function.
      2. How shall that be done?
      3. I want newline after every attribute and element.
      4. How to define one's own print Writer.
      5. How can we add prolog or stylesheet using CompactWriter?

  104. I am new to JSON , is there any way to validate a json- key value pair

    not as part of some larger application) then try the jsonlint.com service. Sample syntax-check with Gson using lombok Output Err stderr Out stdout) . .. details

    1. package com.stackoverflow.so13701022
    2. import com.google.gson.Gson
    3. import com.google.gson.GsonBuilder
    4. import com.google.gson.JsonSyntaxException
    5. import com.google.gson.annotations.SerializedName
    6. import lombok.Data
    7. public class CheckJson {
    8. @Data
    9. private static class LineOfBusiness {
    10. @SerializedName("LOB1")
    11. private String lob1
    12. @SerializedName("LOB2")
    13. private String lob2
    14. @SerializedName("LOB3")
    15. private String lob3
    16. @SerializedName("LOB4")
    17. private String lob4
    18. }
    19. @Data
    20. private static class Market {
    21. @SerializedName("MKTID001")
    22. private String mktid001
    23. @SerializedName("MKTID002")
    24. private String mktid002
    25. @SerializedName("LOB3")
    26. private String lob3
    27. @SerializedName("LOB4")
    28. private String lob4
    29. }
    30. private static final String ONE =
    31. "{"
    32. + " LOB1 : \"LOBAppType=sadfsd\","
    33. + " LOB2 : \"LOBAppType=asdf\","
    34. + " LOB3 : \"LOBAppType=asdf}"
    35. + " LOB4 : \"LOBAppType=sdf\","
    36. + "}"
    37. // I corrected this one on purpose private static final String TWO = "{" + " MKTID001 :\"MarketName=US||Descr=USA\"," + " MKTID002 :\"MarketName=JP||Descr=Japan\"," + " LOB3 : \"LOBAppType=asdf\"," + " LOB4 : \"LOBAppType=sdf\"" + "}"
    38. public static void main(String[] args) {
    39. final Gson gson = new GsonBuilder().create()
    40. System.out.println(tryParse(gson, ONE, LineOfBusiness.class))
    41. System.out.println(tryParse(gson, TWO, Market.class))
    42. }
    43. private static <T> T tryParse(Gson gson, String what, Class<T> clazz) {
    44. try {
    45. return gson.fromJson(what, clazz)
    46. } catch (final JsonSyntaxException e) {
    47. System.err.println(e)
    48. }
    49. return null
    50. }
    51. }

    Positive Reactions
    1. Is there any way to do it dynamically.
    Other Reactions
    1. actually i am loading these objects from a js file.

  105. I am new to JSON , is there any way to validate a json- key value pair

    None .. details

    1. (Err) com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 159(Out) null(Out) CheckJson.Market(mktid001=MarketName=US||Descr=USA, mktid002=MarketName=JP||Descr=Japan, lob3=LOBAppType=asdf, lob4=LOBAppType=sdf)

  106. Null Pointer while converting to JSON

    solved Some of the events field values were NULL in DB and this was the Cause. In eventArrayList refers ArrayList<ArrayList and few field values in ArrayList were NULL From above Ex Look into the Null value in inner arraylist which is at second index After removing the Null values from the inner ArrayList things are working fine. .. details

    1. {events=[[98, EvebtTitle, Mon Dec 03 2012 10:45:00 +0530, Wed Oct 17 2012 11:15:00 +0530, 0, 0, 0, 0, 1, NJ, ], [118, testDec, Wed Dec 05 2012 09:00:00 +0530, Wed Dec 05 2012 10:00:00 +0530, 0, 0, 0, null, 1, null, ]]}

    • See Also (3)
    1. Skip root element while deserializing json

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. String json
      2. // your jsonStringMapWrapper result = ConvertJsonToObject.getFromJSON(json,MapWrapper.class)

    2. convert foursquare http response to JSON for java

      From my experience if you get the JSON object such as the problem I had parsing a returned LOCATION field. I started with the following code If you can get the Object then simply refer to has parameter like I use has to protect against the empty or null field not being returned. details

      Reactions - Positive 0, Negative 0, Others 0

      1. if(jsonObjLoc.has("myAddress")) { // name of field to look for myTextAddress = jsonObjLoc.getString("address")
      2. }

    3. How to get error text in controller from BindingResult

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. @Autowiredprivate MessageSource messageSource

  107. gson - include class name when serializing java pojo -&gt; json

    This question addresses pretty the same problem as value-includedand the accepted answer is also pretty the same. I don't know if the answer is still interesting you but what you can do is the following . .. details

    1. public static void main(String [] args){ Person one = new Person("Alice")
    2. Person two = new Person("Bob")
    3. List<Person> people = new ArrayList<Person>()
    4. people.add(one)
    5. people.add(two)
    6. Gson gson = new Gson()
    7. JsonElement je = gson.toJsonTree(people)
    8. JsonObject jo = new JsonObject()
    9. jo.add("person", je)
    10. System.out.println(jo.toString())
    11. //prints {"person":[{"name": "Alice"},{"name": "Bob"}]}}

    Positive Reactions
    1. This is exactly what I was looking for thanks.

  108. Jackson deserializing with custom deserializer causes a lot of GC calls and takes a lot longer

    You can definitely write a more efficient version using Streaming API. Something like it is also possible to implement this with data-binding as JsonDeserializer) but it gets bit complicated just because you want to delegate to default deserializer.To do this you would need to implement BeanDeserializerModifier and replace standard deserializer when modifyDeserializer is called your own code can retain reference to the original deserializer and delegate to it instead of using intermediate tree model. .. details

    1. JsonParser jp = mapper.getJsonFactory().createJsonParser(input)
    2. JsonToken t = jp.nextToken()
    3. if (t == JsonToken.START_OBJECT) { return mapper.readValue(jp, classToBindTo)
    4. }return null

    Positive Reactions
    1. Thanks.
    Other Reactions
    1. I have edited my question and added the JSON, the parsing code and the logs.

  109. Mapping a JSONObject to a List with Flexjson in Java / Android

    Then you can wrap it in a List and send it on to the appropriate decoder. Something like Then I think that's roughly what would fix that bug but should also fix your problem. .. details

    1. LibraryResponse response = new JSONDeserializer<LibraryResponse>() .use(Timestamp.class, new TimestampObjectFactory()) .use("library.vendor.values.catalog.values.document", new ListDocumentFactory() ) .deserialize(getLocalLibrary(), LibraryResponse.class)

    Positive Reactions
    1. The good news is you could set it on all List.class because the code isn't tied to any specifics about Document.
    2. Another question: If I specify the Factory to be used on library.vendor.values.catalog.values.document it won't affect other levels as library.vendor.values.document?
    3. So the ObjectFactory layer is before we have a any strong typed object like Document.
    4. Then it uses a series of ObjectFactory to map those simple objects into the actual objects you are mapping into.
    5. Thanks for your answer!
    6. JSONDeserializer first translates the JSON into simple objects like List, Map, String, Number, and Boolean.
    7. Thank you very much for your great support.
    Negative Reactions
    1. Flexjson is great, even when dealing with nasty backend developers ;-).
    2. I think the reason you are getting a List instead of List is a bug in Flexjson.
    3. Anyway, when trying you code I'm getting an Exception at ParameterizedType ptype (ParameterizedType) targetType; java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType.
    4. The use of the Factory on the List.class did the trick finally!
    5. I'm sorry, I think I misunderstood you there.
    6. My first tries failed, though.
    7. I think I made myself not clear, I always get a List but in case there is only one document I don't have Documents in the List but HashMaps, so List as catalog.document instead of List.
    8. I fail to see how my answer didn't answer your problem.
    Other Reactions
    1. As even a vendor can have documents... Would it be possible to specify the factory to be used on LibraryItem.class which is the superclass of all the others?
    2. The hash map objects contain the data connected to the document.
    3. I think I need a Factory that decides if we already have a Document or if we have a HashMap.
    4. For example List?
    5. If the latter I would map the document object manually.
    6. If not then Flexjson won't know what type of object to map the JSON to within the list.
    7. You can set ObjectFactories by class, but in this case you'd need to set it on all List.class.
    8. So you'll plug into that point writing your own ObjectFactory like I showed instead of using the default instance.
    9. Do you think this approach is possible?
    10. If you are getting an exception are you using generics on your instance variables?
    11. Specifying by object path will only use that ObjectFactory for that path (unless you use wildcards).
    12. Seems strange to me.

    • See Also (4)
    1. Deserializing JSON list into list of objects with Flexjson

      I have not tested it but seems it will work. Okay I think I found an acceptable solution although I do not know how optimal it is Will result in a list of books. details

      Reactions - Positive 0, Negative 0, Others 0

      1. List<Book> items = new JSONDeserializer<Map<String,List<Book>>>().use("values.values", Book.class).deserialize(json, Map.class).get("books")

    2. How to force FlexJson in java to deserialize a json object to a string?

      Inside the ObjectFactory it could then turn that into the string and bind that into the object there. . details

      Reactions - Positive 5, Negative 4, Others 0

      1. new JSONDeserializer<...>() .use( "values", Response.class ) .use( "values.Data", new JSONStringTransformer() ) .deserialize( json, Response.class )

      Positive Reactions
      1. Yeah this solution works fine for now.
      2. Thanks for the help!
      3. I was going to suggest just substring'ing it because that would be a lot more efficient.
      4. Ah all right, so what I'm doing is pretty backwards then.
      5. Well even if you could've gotten it to translate the HashMap back to JSON.
      Negative Reactions
      1. There's no way the default StringTransformer would work?
      2. Then it binds the contents of those hash maps into your static typed objects you want.
      3. even if I try to use that I get this error: The method use(String, ClassLocator) in the type JSONDeserializer is not applicable for the arguments (String, StringTransformer).
      4. I tried to mess around with creating a custom object factory but it seemed pretty nasty so I just ended up doing this: int dataIndex JSON.indexOf(dataIdentifier); formattedResponse.Data JSON.substring(dataIndex + dataIdentifier.length() - 2, JSON.length() - 1); Where dataIdentifier is "\"},\"Data\":{\""; This is pretty nasty but it works.
      Other Reactions
      1. You need something that takes JSON into Objects which is ObjectFactory.
      2. I'll look around at how to make custom object factories.
      3. Yes during the intermediate stage.
      4. Out of curiosity, if you have objects in objects, does flexjson make hashmaps of hashmaps?
      5. But the classes that converts things into Strings isn't going to know how to translate a HashMap into a String.
      6. This is a very strange situation where you don't want to take in a portion of the JSON as objects, and instead use the JSON portion string instead.
      7. So JSONStringTransformer should be a custom ObjectFactory that I make?
      8. No StringTransformer won't work because Transformers are used to translate Objects into JSON.

    3. Using Jackson's @JsonTypeInfo with a custom serializer

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonDeserializer.deserializeWithType(...)

    4. How to deserialize a jsonarray into a List<Map> in java using flexjson.deserializer?

      To do that you have to specify the type contained in the list by using the path expression values". Updated Add the new keyword and made the generic types on the right match the left. details

      Reactions - Positive 1, Negative 1, Others 0

      1. Map<String,List<Map<String,String>>> result = new JSONDeserializer<Map<String,List<Map<String,String>>>>() .use("values",List.class) .use("values.values", Map.class) .deserialize( json)
      2. List<Map<String,String>> filterEntries = result.get("filterEntries")

      Positive Reactions
      1. Map> reuslt new JSONDeserializer>>().use("values", List.class).deserialize(json);.
      Negative Reactions
      1. I also get an error that it "cannot convert from List to Map>"Also, I'm attempting something like this but a little less complicated: {"title":["a","b","c"]}'code' Map> result new JSONDeserializer.
      Other Reactions
      1. There seems to be a couple issues with the code above, I'm sure because it wasn't run or something.
      2. But you do need a "new" before JSONDeserializer.

  110. incorrect gson code: Expected BEGIN_OBJECT but was STRING

    Register Type adapter in GsonBuilder and Parse your json context in deserialize method. . .. details

    1. @Override public YourClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context){}

    Other Reactions
    1. "How do I register Type adapter there?"
    2. Look here: URL_http://google - gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html.
    3. Resp is just a string, Should I implement these two interfaces at the class where I am using resp?
    4. How do I register Type adapter there?
    5. No ,the just collection or your class VideoImages.
    6. GsonBuilder is inside jar file.

  111. Parsing Json witth Gson in Java

    They may be similar but I am not having much luck in piecing the pieces together. Strip the results array out of that json leaving nothing outside the s Then this was just about the least I could modify the code to get it working . .. details

    1. import com.google.gson.*
    2. import com.google.gson.reflect.*
    3. import java.io.*
    4. import java.lang.reflect.*
    5. import java.util.*
    6. public class tweetfeedreader {
    7. public static void main(String args[]) throws IOException {
    8. Gson gson = new Gson()
    9. BufferedReader bufferedReader = new BufferedReader(new FileReader("jsonfile.json"))
    10. String line
    11. StringBuilder sb = new StringBuilder()
    12. while ((line = bufferedReader.readLine()) != null) sb.append(line)
    13. Type tweetCollection = new TypeToken<Collection<tweet>>() {}.getType()
    14. Collection<tweet> tweets = gson.fromJson(line, tweetCollection)
    15. for (final tweet t : tweets) System.out.println(t.text)
    16. }
    17. }

    Positive Reactions
    1. hm.. i'm trying to see why it's coughing up NPE, but thanks a lot!.
    Negative Reactions
    1. Sorry - I switched a variable out and put the wrong one back in, change the fromJson(line, to fromJson(sb.toString(),.
    Other Reactions
    1. I've updated the answer.
    2. It is now giving me a output of null.
    3. Should work now.
    4. let us [continue this discussion in chat]( URL_http://chat.stackoverflow.com/rooms/17986/discussion-between-whitebit - and-rich).
    5. I copied everything from URL_http://search.twitter.com/search.json?q=%40android into jsonfile.json.
    6. You're probably right, but I'm getting a NullPointerException at the foreach loop at the end.
    7. Can you provide the contents of jsonfile.json?
    8. Just tried it.

  112. How can I iterate JSONObject to get individual items

    None .. details

    1. Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}

  113. Converting Map&lt;String,String&gt; into json

    Have a look at example 1.4 on this page simple/wiki/EncodingExamples#Example_1-4_-_Encode_a_JSON_object Using_Map_and_streaming simple/wiki/EncodingExamples#Example_1-4_-_Encode_a_JSON_object Using_Map_and_streaming . You can also try something like this with Gson Library The output look like this . .. details

    1. package com.stackoverflow.works
    2. import com.google.gson.Gson
    3. import com.google.gson.reflect.TypeToken
    4. import java.lang.reflect.Type
    5. import java.util.HashMap
    6. import java.util.Map
    7. /* * @Author: sarath_sivan */ public class MapToJsonConverter {
    8. /* * @Description: Method to convert Map to JSON String * @param: map Map<String, String> * @return: json String */
    9. public static String convert(Map<String, String> map) {
    10. Gson gson = new Gson()
    11. String json = gson.toJson(map)
    12. return json
    13. } /* * @Description: Method to convert JSON String to Map * @param: json String * @return: map Map<String, String> */
    14. public static Map<String, String> revert(String json) {
    15. Gson gson = new Gson()
    16. Type type = new TypeToken<Map<String, String>>() {}.getType()
    17. Map<String, String> map = gson.fromJson(json, type)
    18. return map
    19. } /* * @Description: Method to print elements in the Map * @param: map Map<String, String> * @return: void */
    20. public static void printMap(Map<String, String> map) {
    21. for (String key : map.keySet()) {
    22. System.out.println("map.get(\"" + key + "\") = " + map.get(key))
    23. }
    24. } /* * @Description: Method to print the JSON String * @param: json String * @return: void */
    25. public static void printJson(String json) {
    26. System.out.println("json = " + json)
    27. } /* * @Description: Main method to test the JSON-MAP convert/revert logic */
    28. public static void main(String[] args) {
    29. Map<String, String> paymentCards = new HashMap<String, String>()
    30. paymentCards.put("card_switch", "Master")
    31. paymentCards.put("issuing_bank", "ICCI")
    32. paymentCards.put("card_Type", "DebitCard")
    33. String json = convert(paymentCards)
    34. //converting Map to JSON String System.out.println("Map to JSON String")
    35. System.out.println("******************")
    36. printJson(json)
    37. System.out.println()
    38. paymentCards = revert(json)
    39. //converting JSON String to Map System.out.println("JSON String to Map")
    40. System.out.println("******************")
    41. printMap(paymentCards)
    42. }
    43. }

    • See Also (4)
    1. JSON/GSON with changing keys into Java

      With Gson here's what that solution would look like. The following update generates a list of currencies from the currency data in the deserialized map. details

      Reactions - Positive 5, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.annotations.SerializedName
      3. import com.google.gson.reflect.TypeToken
      4. import java.io.FileReader
      5. import java.lang.reflect.Type
      6. import java.math.BigDecimal
      7. import java.util.Map
      8. public class Foo {
      9. public static void main(String[] args) throws Exception {
      10. Gson gson = new Gson()
      11. Type currencyMapType = new TypeToken<Map<String, Currency>>() {}.getType()
      12. Map<String, Currency> currencyMap =
      13. gson.fromJson(new FileReader("input.json"), currencyMapType)
      14. System.out.println(currencyMap)
      15. }
      16. }
      17. class Currency {
      18. @SerializedName("7d")
      19. BigDecimal _7d
      20. @SerializedName("30d")
      21. BigDecimal _30d
      22. @SerializedName("24h")
      23. BigDecimal _24h
      24. @Override
      25. public String toString() {
      26. return String.format("{7d:%s, 30d:%s, 24h:%s}", _7d, _30d, _24h)
      27. }
      28. }

      Positive Reactions
      1. I know my fair share about Java, but have only used ArrayLists and the like.
      2. "is there a way to include the currency code like USD in the object?"
      3. This is much better, but is there a way to include the currency code like USD in the object?
      4. I was trying to do something like this, but couldn't get it to work.
      5. My android app is pretty much complete, except for the part where when I try to actually download that json from the internet, I get a stub error.
      Negative Reactions
      1. -- Yes, but it would require custom deserialization processing, which is not terribly involved, but since the JSON structure is such a poor fit for the target Java data structure, it's a little easier to just transform the Java objects into what you want after performing the simple deserialization steps demonstrated above.
      Other Reactions
      1. I've never used maps before."
      2. I've never used maps before.
      3. "How do you access the data once it's in that map?
      4. I've taken my school's AP Comp Sci course, but we only learned the minimum to take the AP test.
      5. -- I suggest learning the basics first.
      6. I'll post example code for doing so, which will include getting data out of the Map.
      7. How do you access the data once it's in that map?
      8. I've been told it's because I'm using the emulator, and actually need a device, which I don't have.
      9. There are plenty of online resources to learn how to program in Java.
      10. I found a work around before you posted this.

    2. Help me to parse this kind of json for android

      Here's what that would look like. . details

      Reactions - Positive 2, Negative 0, Others 0

      1. public class Foo {
      2. public static void main(String[] args) throws Exception {
      3. Gson gson = new Gson()
      4. Type thingsType = new TypeToken<List<Vulume>>() {}.getType()
      5. List<Vulume> things = gson.fromJson(new FileReader("input.json"), thingsType)
      6. System.out.println(gson.toJson(things))
      7. }
      8. }
      9. class Vulume {
      10. String id
      11. String name
      12. String status
      13. List<Vulume> vulumes
      14. }

      Positive Reactions
      1. Thank you for your reply!
      2. An example of the above helped me, I'm right understand that i can get exact key: value from my class in json?

    3. Parsing Gson with Json not working for Android

      The JSON structure is Here is such an example using the same JSON as in the original question. . details

      Reactions - Positive 3, Negative 3, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.reflect.TypeToken
      3. import java.io.FileReader
      4. import java.lang.reflect.Type
      5. import java.util.ArrayList
      6. public class Foo {
      7. public static void main(String[] args) throws Exception {
      8. Gson gson = new Gson()
      9. Type collectionType = new TypeToken<ArrayList<ArticleContainer>>() {}.getType()
      10. ArrayList<ArticleContainer> articles =
      11. gson.fromJson(new FileReader("input.json"), collectionType)
      12. System.out.println(gson.toJson(articles))
      13. }
      14. }
      15. class ArticleContainer {
      16. Article article
      17. }
      18. class Article {
      19. public int author_id
      20. public String body
      21. public String catagory
      22. public String created_at
      23. public int id
      24. public String published
      25. public String updated_at
      26. }

      Positive Reactions
      1. Thanks a million!.
      2. thanks for your reply :).
      3. I'm parsing something similar which explained in hour example... the problem i cant parse is: "classification":"ab 0","genres":"Drama","trailer": {"de": [{"id":"11471452", "name":"Trailer 1", "hq":false}],"ov":[]},"trailer_url":"xxx",... beginning with trailer.. its just one entry there, everything else works...
      Negative Reactions
      1. thanks a lot for your response... the format in comments is really bad :) so thanks for your advice, for now i have found a workaround.
      2. but i think i've found this problem a few times on the web, but wasnt able to understand the solution.
      3. I#m sorry, i dont understand how to use this....
      Other Reactions
      1. That was exactly the tweak I needed.
      2. @cV2 -- If you have a question, I suggest creating a new post.

    4. Deserialize JSON to Collection of Unknown Types

      Here's an example that demonstrates this point. input.json Contents Foo.java The output of this example is . details

      Reactions - Positive 2, Negative 1, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.reflect.TypeToken
      3. import java.io.FileReader
      4. import java.lang.reflect.Type
      5. import java.util.Map
      6. public class Foo {
      7. public static void main(String[] args) throws Exception {
      8. Gson gson = new Gson()
      9. Type mapOfStringObjectType = new TypeToken<Map<String, String>>() {}.getType()
      10. Map<String, String> map = gson.fromJson(new FileReader("input.json"), mapOfStringObjectType)
      11. System.out.println(map)
      12. }
      13. }

      Positive Reactions
      1. Gson issue 325 addresses simple deserialization to Map.
      2. Please don't hesitate to vote for its implementation at URL_http://code.google.com/p/google - gson/issues/detail?id=325.
      Negative Reactions
      1. Note that Jackson ( URL_http://jackson.codehaus.org ) can deserialize the example JSON above to a Map without custom processing, and JSON-lib ( URL_http://json - lib.sourceforge.net) can similarly deserialize to a Map (Map map JSONObject.fromObject(json);).
      Other Reactions
      1. I don't know for sure, as I haven't yet try to do so.
      2. Note, a previous comment I made on this subject was for a previous version of Gson.
      3. With the implementation of Gson issue 325, it may now work to just deserialize to Map.

  114. What is the data structure of this JSON?

    It only requires control for the name of the fields. To deserialize Try that and see if that works. .. details

    1. String json = ...
    2. DataContainer myDataContainer = new Gson().fromJson(JSONString , DataContainer.class)
    3. Result[] myResult = myDataContainer.d.results

    Positive Reactions
    1. yes, that works!
    2. Thanks very much.
    Negative Reactions
    1. Sorry, it's been a couple months since I worked with Gson, so I totally missed it.
    Other Reactions
    1. It's because there's an initial opening { that we forgot about.
    2. That indicates the start of an object, and "d" is a field within that object.
    3. D myD new Gson().fromJson(JSONString , D.class); Result[] myResult myD.results; I got nothing.
    4. :(.
    5. I try that, but still get null.
    6. So as there is a '{' before 'd', we should set up a class that contains 'd'.

  115. How could I parse json into java

    I just don't know the data structure of this Json String. . .. details

    1. import com.google.gson.Gson
    2. import java.io.IOException
    3. public class GsonDemo {
    4. public static void main(String[] args) {
    5. Gson gson = new Gson()
    6. try {
    7. String json = ""
    8. // your json string //convert the json string to object YourObject obj = gson.fromJson(json, YourObject.class)
    9. } catch (IOException e) {
    10. e.printStackTrace()
    11. }
    12. }
    13. }

  116. How to parse json string to ArrayList&lt;NameValuePair&gt;

    I think the below code is helpful for you. . .. details

    1. Type type = new TypeToken<ArrayList<BasicNameValuePair>>() {}.getType()

    Positive Reactions
    1. Thanks.
    Other Reactions
    1. Ah.
    2. Never thought BasicNameValuePair would be the answer to it.

  117. Gson custom deseralizer for one variable in an object

    I faced the same problem. I think my solution is slightly simpler and more generic Of course I agree with the original poster the best solution is to change the json. .. details

    1. Gson gson = new GsonBuilder() .registerTypeAdapter(List.class, new JsonSerializer<List<?>>() { @Override public JsonElement serialize(List<?> list, Type t, JsonSerializationContext jsc) { if (list.size() == 1) { // Don't put single element lists in a json array return new Gson().toJsonTree(list.get(0))
    2. } else { return new Gson().toJsonTree(list)
    3. } } }).create()

    • See Also (1)
    1. how to prepare json file using gson library

      For the sake of completeness I'll also point out that a simple custom serializer could be employed to solve this problem. And of course one could construct a JsonElement tree from the original Java data structure then manipulate the JSON tree to match the desired output and finally serialize it. details

      Reactions - Positive 0, Negative 0, Others 0

      1. import com.google.gson.Gson
      2. import com.google.gson.GsonBuilder
      3. import com.google.gson.JsonElement
      4. import com.google.gson.JsonSerializationContext
      5. import com.google.gson.JsonSerializer
      6. import java.lang.reflect.Type
      7. import java.util.ArrayList
      8. import java.util.List
      9. public class Foo {
      10. public static void main(String[] args) throws Exception {
      11. Person person = new Person("name1", 1)
      12. Address address = new Address("home1", "office1")
      13. SomeContainer thing = new SomeContainer(person, address)
      14. GsonBuilder gsonBuilder = new GsonBuilder()
      15. gsonBuilder.registerTypeAdapter(Person.class, new MyCustomSerializer())
      16. Gson gson = gsonBuilder.create()
      17. System.out.println(gson.toJson(thing))
      18. }
      19. }
      20. class MyCustomSerializer implements JsonSerializer<Person> {
      21. @Override
      22. public JsonElement serialize(Person src, Type typeOfSrc, JsonSerializationContext context) {
      23. List<Person> personList = new ArrayList<Person>()
      24. personList.add(src)
      25. return new Gson().toJsonTree(src)
      26. }
      27. }
      28. class SomeContainer {
      29. Person person
      30. Address address
      31. SomeContainer(Person p, Address a) {
      32. person = p
      33. address = a
      34. }
      35. }
      36. class Person {
      37. private String name
      38. private int id
      39. Person(String n, int i) {
      40. name = n
      41. id = i
      42. }
      43. }
      44. class Address {
      45. private String homeaddress
      46. private String officeaddress
      47. Address(String h, String o) {
      48. homeaddress = h
      49. officeaddress = o
      50. }
      51. }

  118. Getting a 400 Error on Ajax call with JSON

    None .. details

    1. $.ajax({ url : '/my_project/rest/runs/1234', type : 'POST', data: JSON.stringify({ job_position : 38, token: 'moo' }), contentType: 'application/json', dataType: 'json', success : function(html) { }})

    • See Also (2)
    1. Getting a 400 Error on Ajax call with JSON

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. $.ajax({ url : '/my_project/rest/runs/1234', type : 'POST', data: { "job_position" : 38, "token" : "moo"}, contentType: 'application/json', dataType: 'json', success : function(html) { } })

    2. How do I send a json object from my rest service so I can parse in out on the client side javascript

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. <head><script src="jquery-1.6.js"></script> <!--AJAX FOR STATUS PAGE REFRESH --> <script type="text/javascript"> //when page is ready do the following $(document).ready(function() { // Disable caching of AJAX responses $.ajaxSetup ({cache: false})
      2. //set interval of refresh setInterval(doAjaxStuff, 1000)
      3. //function to call to fire off ajax function doAjaxStuff() { $.ajax ({ url: "status", // <-- this refers to the Controller function above called "status()" dataType: 'json', success: function(json) { //traverse throught each element in the incoming JSON object for(var i = 0
      4. i< json.length
      5. i++) { if(json[i].status == "ACTIVE") { $("#Status"+json[i].id).html("Running")
      6. } } } })
      7. } })
      8. </script></head>

  119. Skip root element while deserializing json

    None .. details

    1. public class MyDeserialiser implements JsonDeserializer<MapWrapper> {
    2. @Override
    3. public MapWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx)
    4. throws JsonParseException {
    5. JsonObject _global = json.getAsJsonObject()
    6. _global = _global.