Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

why ? to json return null #1872

Closed
YanQin-JAVA opened this issue Mar 5, 2021 · 2 comments
Closed

why ? to json return null #1872

YanQin-JAVA opened this issue Mar 5, 2021 · 2 comments

Comments

@YanQin-JAVA
Copy link

   public static void main(String[] args) throws JsonProcessingException {
	class User{
		private String a;

		public User() {
		}

		public User(String a) {
			this.a = a;
		}

		@Override
		public String toString() {
			return "User{" +
					"a='" + a + '\'' +
					'}';
		}

		public String getA() {
			return a;
		}

		public void setA(String a) {
			this.a = a;
		}
	}

	ArrayList<Object> users = Lists.newArrayList(new User("a"), new User("b"));
	Gson gson = new GsonBuilder().create();
	String s = gson.toJson(new User("c"));
	String s1 = (new ObjectMapper()).writeValueAsString(users);
	System.out.println("s = " + s);
	System.out.println("s1 = " + s1);


}

//return :
s = null
s1 = [{"a":"a"},{"a":"b"}]

@YanQin-JAVA
Copy link
Author

gson version : 2.8.6

@YanQin-JAVA YanQin-JAVA changed the title to json return null why ? to json return null Mar 5, 2021
@Marcono1234
Copy link
Collaborator

Marcono1234 commented Mar 5, 2021

Local classes are not supported. See #1510 and https://github.com/google/gson/blob/master/UserGuide.md#finer-points-with-objects. To solve this make User either a top-level class or a static nested class.

(comment copied from lyubomyr-shaydariv's comment here)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants