com.google.gson.Jsonsyntaxexception: java.lang.Illegalstateexception: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

Asked

Viewed 2,449 times

1

Hi, I’m new here and I’d like a hand.

I happen to be developing a work of distributed systems in which the client is in Java and the server in Python. For there to be communication between the two, you need to use Json. The problem is that when receiving Json from the server and trying to convert to a java object the following error occurs:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:927)

Details

Python server

from socket import *
import json

serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)

print('The server is ready to receive')
while True:
connectionSocket, addr = serverSocket.accept()

x = connectionSocket.recv(1024)

y = json.loads(x)

print(y)

print(y["messageType"])
print(y["requestId"])
print(y["objectReference"])
print(y["methodId"])
print(y["arguments"])

w = {
    'messageType': int(y["messageType"]) - 25,
    'requestId': int(y["requestId"]) * (-1),
    'objectReference': y["objectReference"].upper(),
    'methodId': int(y["methodId"]) + 100,
    'arguments': y["arguments"]
}

z = json.dumps(w)
connectionSocket.send(bytes(z + "\r\ntrue)", 'UTF-8'))

connectionSocket.close()

Java client code where I send Json to the server and get the response

Message messageRetorno = null;

//Código extra aqui//

thy{
    Message message = new Message(0, requestId, objeto, methodId, arguments);
    String json = userJson.MessageToGson(message);

    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    Writer out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8));

    out.write(json);
    out.flush();

    while(controle){
    messageRetorno = userJson.MessageFromGson(in.readLine());

        if(messageRetorno.getRequestId() == requestId && messageRetorno.getMessageType() == 1){
        requestId += 1;
            controle = false;
        }
        else{
            out.write(json);
            out.flush();
            repeat += 1;
        }

        if(repeat == 20){
            return null;
        }

The class Message which reference contains only the attributes of the object I want to create from the json I receive.

Finally, I have the function Messageformjson which is in another class, which is responsible for converting the received json into a Message type object and returning that object. However, I can convert to the object, print its attributes after the conversion, but I cannot return and gives the error shown above.

Messagefromjson function

public Message MessageFromGson(String json){
    Message m = gson.fromJson(json, Message.class);
    System.out.println(m.toString());
    System.out.println("\n\nPegando métodos\n");
    System.out.println(m.getMessageType());
    System.out.println(m.getRequestId());
    System.out.println(m.getObjectReference());
    System.out.println(m.getMethodId());
    System.out.println(m.getArguments());

    return m;
}

Output from function execution above

Message Type: -25
Request Id: 0
Object Reference: TESTEOBJETO
Method Id: 112
Arguments: asdf


Pegando métodos

-25
0
TESTEOBJETO
112
asdf

Finally, the following is the code of the test class that I use only to test json

Client cliente = new Client();
cliente.doOperation("testeObjeto", 12, "asdf");

I know it’s a very long doubt, but if you can help me, I’d be grateful.

1 answer

0

The first line of the stacktrace already says what the problem is:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

Your python server is returning a string instead of a Json, the answer has to start with { but is starting with another character probably ". Test the response with a client like Postman to make sure what is being received by java.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.