2
Unexpected character () at position 0.
    at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
    at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
    at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
    at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
    at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
    at net.ddns.coolpvp.Testing.main(Testing.java:22)

I was making a TCP Server on Java, it was receiving a json and it gave this error, but I checked and the first character is '{', how can I fix this? I have no clue. I would be very grateful if you could help me
EDIT: The JSON is generated by .NET Framework in a C# Application and this is a JSON

{"Type":"level-info","LevelNumber":1}

This is how the C# Application is generating the JSON
Program.cs

using System;
using System.Text;
using System.Net.Sockets;
using System.IO;

namespace Testing
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            TcpClient client = new TcpClient();
            client.Connect("localhost", 152);
            StreamWriter writer = new StreamWriter(client.GetStream(), Encoding.UTF8) { AutoFlush = true };
            writer.WriteLine(new RequestLevelInfo(1).ToJSONString());
            client.Close();
            Console.ReadKey(true);
        }
    }
}

RequestLevelInfo.cs

using System.Web.Script.Serialization;

namespace Testing
{
    public class RequestLevelInfo
    {
        public string Type { get { return "level-info"; } }
        public int LevelNumber { get; }
        public RequestLevelInfo(int level)
        {
            LevelNumber = level;
        }
        public string ToJSONString()
        {
            return new JavaScriptSerializer().Serialize(this);
        }
    }
}

The Server is reading it using a BufferedReader using the readLine method

package testing;

import java.net.Socket;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class Testing {
    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket();
            server.bind(new InetSocketAddress(InetAddress.getByName("localhost"), 152));
            Socket client = server.accept();
            BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
            String dataReceived = reader.readLine();
            JSONObject json = (JSONObject)new JSONParser().parse(dataReceived);
            System.out.println(json.toJSONString());
            client.close();
            server.close();
        } catch (IOException ex) {
            ex.printStackTrace(System.err);
        } catch (ParseException ex) {
            ex.printStackTrace(System.err);
        }
    }
}
  • Can you include your JSON in your question? – Adam Neuwirth Jul 13 '20 at 17:22
  • How is the JSON content generated and sent to the server? How does the server read it? Please include the code in the question – Joni Jul 13 '20 at 17:25
  • Please also show us your JSON file so that we can see if the error is due to the JSON file. – Verity Jul 13 '20 at 17:26
  • 1
    Did you use something like .writeUTF(String), because this method prepends two bytes as length at the beginning, like [0x00][0x01][a]? – JCWasmx86 Jul 13 '20 at 17:35
  • So as far as I can see the error is not due to the JSON file, could you also show us the code with which you read the JSON file? – Verity Jul 13 '20 at 18:19
  • Let me think about it... – Verity Jul 13 '20 at 18:31
  • Are you using the same encoding on both ends? It looks like the writer is using Unicode (a.k.a. UTF-16), but the `InputStreamReader` does not specify. I would use UTF-8 on both ends if possible. – Brian Rogers Jul 13 '20 at 19:50

2 Answers2

2

The problem is in your C# code: it's sending incorrect JSON.

You are using the Encoding.UTF8 object. This object includes an invisible and unnecessary "byte order marker" character, which the Java JSON parser does not understand. JSON "must not" use a byte order mark character: JSON Specification and usage of BOM/charset-encoding

The solution is to create your own instance of UTF8Encoding. For example:

UTF8Encoding jsonEncoding = new UTF8Encoding(false);
StreamWriter writer = new StreamWriter(client.GetStream(), jsonEncoding) { AutoFlush = true };
Joni
  • 101,441
  • 12
  • 123
  • 178
1

Hello, I thought about your code and changed something, here is my code:

public static void main(String[] args) {

    try {
        BufferedReader bufferedReader = java.nio.file.Files.newBufferedReader(Paths.get("test.json"));
        JSONObject data = (JSONObject) new JSONParser().parse(bufferedReader);
        System.out.println(data.get("Type"));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

This is the content of the test.json File: {"Type":"level-info","LevelNumber":1}

My output is: level-info

Please check if you really have org.json.simple.JSONObject, org.json.simple.parser.JSONParser and org.json.simple.parser.ParseException imported. Not that you accidentally imported anything else.

Have fun, I hope I could help you!

EDIT

So, for me the error occurred with the following example:

public static void main(String[] args) {

    try {
        String string = "{name=Asel, number1=40.34, number2=29.343}";
        JSONObject object = (JSONObject) new JSONParser().parse(string);
        System.out.println(object.get("name"));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

But not with this:

public static void main(String[] args) {

    try {
        String string = "{\"name\":\"Asel\", \"number1\":\"40.34\", \"number2\":\"29.343\"}";
        JSONObject object = (JSONObject) new JSONParser().parse(string);
        System.out.println(object.get("name"));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Therefore I wonder if your string that you really get from your TCP socket is exactly {"Type":"level-info","LevelNumber":"1"} and not something wrong liek this: {"Type"="level-info","LevelNumber"="1"}

To test it you could try to replace = with : in the string of TPC Socket and see if the error still occurs.

JSONObject json = (JSONObject)new JSONParser().parse(dataReceived.replace("=", ":"));

Verity
  • 215
  • 1
  • 10
  • So, that's basically what I did, but I was reading from a file, I was actually reading from a BufferedReader that was reading from an InputStreamReader that was reading from a TCP Socket, so I can't actually do that – Rodrigo Santos Jul 13 '20 at 18:45
  • Ok, wait a second – Verity Jul 13 '20 at 18:46
  • I edited my answer, but unfortunately I can't test it with a socket connection right now, but I can also do it from the file readen with a buffered reader. – Verity Jul 13 '20 at 18:52
  • I don't think parsing from the reader is good for me, because in this server I have to read a couple more times, can you look at the entire code that I posted now to see if there's any mistake? Or something that I am missing on? Thank you for the attention – Rodrigo Santos Jul 13 '20 at 18:57
  • Yes I can wait a second – Verity Jul 13 '20 at 18:59
  • What do you get when you print "client.getInputStream().toString" in the console? – Verity Jul 13 '20 at 19:00
  • can you please send the code from Testing.java class line 22? – Verity Jul 13 '20 at 19:03
  • The Line 22 is 'JSONObject json = (JSONObject)new JSONParser().parse(dataReceived);' and when I print that I get 'java.net.SocketInputStream@75b84c92' – Rodrigo Santos Jul 13 '20 at 19:07
  • Ok, I just got the same error and am trying to fix it, then I will send you my answer :D – Verity Jul 13 '20 at 19:09
  • Take a look at my answer below "EDIT" :D – Verity Jul 13 '20 at 19:31
  • I already tested what it receives and it actually receives the correct JSON, but if you want to get the same exact error that I got just copy paste the code and try to change it, I am in this problem for 3 hours now, I have tried everything since checking the received data to completly changing how I read it and nothing has worked – Rodrigo Santos Jul 13 '20 at 19:36
  • I am sorry, but unfortunately I don't know what to do next, but I would still be happy about a positive rating. But if you really want, I can try to run your entire code on my PC tomorrow and try to fix it again? – Verity Jul 13 '20 at 19:40
  • Thanks for the help, I'll give you a positive rating because you really tried to help, if you could run my entire code that would be great. Thank you for taking time to try to help me – Rodrigo Santos Jul 13 '20 at 19:45
  • Ok thanks for your upvote or whatever, I'll try again tomorrow – Verity Jul 13 '20 at 19:46