There is a class User:
public class User{ private String login; private String password; public User(){ this(null, null); } public User(String login, String password){ this.login = login; this.password = password; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password=password; } } I will convert it to a JSON string using this code here:
public String toJson(Object obj){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); try{ return gson.toJson(obj); }catch(JsonSyntaxException jse){ return null; } } And I send the string from the client to the server (All the work of the client and the server is implemented on the sockets), and on the server I create an object using this code, from the string that came from the client:
public <T> T fromJson(String json, Class<T> classOfT){ Gson gson = new GsonBuilder().create(); try{ return gson.fromJson(json, classOfT); }catch(JsonSyntaxException jse){ return null; } } But an error is displayed on the server:
Exception in thread "Thread-0" java.lang.NullPointerException at chat.server.ChatServer.onReceiveString (ChatServer.java:49) // In this line, I'm trying to call getLogin () from a class created from a JSON string
at chat.network.TCPConnection $ 1.run (TCPConnection.java:35) // Here is the code that reads the string that came from the client
at java.lang.Thread.run (Thread.java:748)
I will not understand what the problem is. Testing purely on the client to convert an object to a JSON string and create an object from the same JSON string, and everything works, and if I send this string to the server, then the server cannot create an object.
Addition:
com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 2 path $. at com.google.gson.Gson.fromJson(Gson.java:897) at com.google.gson.Gson.fromJson(Gson.java:852) at com.google.gson.Gson.fromJson(Gson.java:801) at com.google.gson.Gson.fromJson(Gson.java:773) at chat.server.ChatServer.fromJson(ChatServer.java:83) at chat.server.ChatServer.onReceiveString(ChatServer.java:48) at chat.network.TCPConnection$1.run(TCPConnection.java:35) at java.lang.Thread.run(Thread.java:748) Caused by: java.io.EOFException: End of input at line 1 column 2 path $. at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1401) at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:494) at com.google.gson.stream.JsonReader.hasNext(JsonReader.java:414) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:214) at com.google.gson.Gson.fromJson(Gson.java:887) ... 7 more
return null;addjse.printStackTrace();it will be easier to understand what the problem is. - Sergey Gornostaev