question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Nested generic collections don't return jsonized values on toJson

See original GitHub issue
+  private static class ClassWithDistinguishableFieldName {
+    private String distinguishableFieldName = "distinguishableFieldValue";
+  }
+
+  private static class ClassWithHashMapField {
+    private String a = "a";
+    private String b = "b";
+    HashMap<String, Object> c = new HashMap<String, Object>();
+
+    ClassWithHashMapField() {
+      c.put("someArray", Arrays.asList(new 
ClassWithDistinguishableFieldName()));
+    }
+  }



+    ClassWithHashMapField o = new ClassWithHashMapField();
+    String json = gson.toJson(o);

json:
  {"a":"a","b":"b","c":{"someArray":{}}}

expected:
  {"a":"a","b":"b","c":{"someArray":[{"distinguishableFieldName":"distinguishableFieldValue"}]}}


This issue was blocking a project I am working on; so I attached a patch with a 
test.

Original issue reported on code.google.com by masahji%...@gtempaccount.com on 28 Jun 2010 at 2:47

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:14

github_iconTop GitHub Comments

1reaction
GoogleCodeExportercommented, Mar 19, 2015
Can this be a solution?

--------------------------------------------------------------------------------
-------------------------------
package com.github.gimmi.spikegson;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertEquals;

public class StringTemplateBuilderTest {
    private static class CustomType {
        public String value = "a value";
    }

    @Test
    public void should_serialize_custom_type_in_map_with_type_token() {
        Map<String, Object> obj = new HashMap<String, Object>();
        obj.put("k1", new CustomType());

        Type type = new TypeToken<Map<String, Object>>() {
        }.getType();

        String actual = new Gson().toJson(obj, type).replace('"', '\'');

        assertEquals("{'k1':{}}", actual);

        actual = new GsonBuilder().registerTypeAdapter(Object.class, new JsonSerializer<Object>() {
            @Override
            public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context) {
                return context.serialize(src);
            }
        }).create().toJson(obj, type).replace('"', '\'');

        assertEquals("{'k1':{'value':'a value'}}", actual);
    }
}
--------------------------------------------------------------------------------
-------------------------------

Original comment by gianmarco.gherardi on 13 Apr 2011 at 5:43

0reactions
GoogleCodeExportercommented, Mar 19, 2015
Decision which accepted by developers, to use the "static information about the 
type of", generate extremely delusional behavior of Gson:

----
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Arrays;
import java.util.List;

public class Test {
  public static void main(String args[]) {
    Result result = new Result();
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    gson.toJson(result, System.out);
  }

  interface Column {
  }

  static class ColumnImpl implements Column {
    private final String one;
    private final int two;  
    private final Boolean three;

    public ColumnImpl(String one, int two, Boolean three) {
      this.one = one;
      this.two = two;
      this.three = three;
    }
  }

  static class Result {
    private List<ColumnImpl> columnImpls = Arrays.asList(
      new ColumnImpl("one", 2, false), 
      new ColumnImpl("two", 4, true), 
      new ColumnImpl("three", 8, false));
    private List<Column> columns = (List)columnImpls;
  }
}
------


print:


------
{
  "columnImpls": [
    {
      "one": "one",
      "two": 2,
      "three": false
    },
    {
      "one": "two",
      "two": 4,
      "three": true
    },
    {
      "one": "three",
      "two": 8,
      "three": false
    }
  ],
  "columns": [
    {},
    {},
    {}
  ]
}
------

For what has been chosen such behavior?

Original comment by radio...@ya.ru on 28 Jul 2011 at 11:30

Read more comments on GitHub >

github_iconTop Results From Across the Web

(de)serialising Nested Generics in Jackson - Stack Overflow
When Jackson is deserializing your JSON into an object of type A , it sees the following when deserializing for its B field....
Read more >
Parsing JSON with Circe | Baeldung on Scala
As a result, we get either a ParsingError or a Json object. We'll then use the match statement to distinguish between the returned...
Read more >
Nested JSON - HTTPie 3.2.1 (latest) docs
This tells HTTPie to create an array in the given path (if there is not one already), and append the given value to...
Read more >
Migrate from Newtonsoft.Json to System.Text.Json - .NET
Deserialize JSON null literal to non-nullable value types ... NET Core, you don't need to do anything to get behavior like Newtonsoft.Json ....
Read more >
Gson — Mapping of Nested Objects - Future Studio
Getting Started with Java-JSON Serialization & Deserialization ... We don't want you to get bored, so we're going to move away from the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found