Reputation: 145
I am trying to read this JSON code
{
"metadata": {
"clientTransactionId": "",
"serverTransactionId": "20160621101521362-domainrobot-demo.routing-18997-0"
},
"responses": [
{
"domainName": "test.la",
"domainNameUnicode": "test.la",
"domainSuffix": "la",
"earlyAccessStart": null,
"extension": "la",
"generalAvailabilityStart": "2000-01-01T00:00:00Z",
"landrushStart": null,
"launchPhase": "generalAvailability",
"registrarTag": null,
"status": "registered",
"sunriseStart": null,
"transferMethod": "authInfo"
}
],
"status": "success",
"warnings": []
}
With my Java Program:
import javax.json.*;
import java.nio.charset.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.*;
public class Main {
public static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
public static void main(String[] args) throws IOException {
String jsonData = readFile("/home/maltepraktikant/workspace/DomainCreator/bin/JsonData.txt", StandardCharsets.UTF_8);
JsonReader jsonreader = Json.createReader(new StringReader(jsonData));
JsonObject object = jsonreader.readObject();
System.out.println(object);
jsonreader.close();
}
}
I have tried different things, but I haven't found a solution yet. It just gives me the error:
Exception in thread "main" javax.json.stream.JsonParsingException: Unexpected char 65.279 at (line no=1, column no=1, offset=0)
at org.glassfish.json.JsonTokenizer.unexpectedChar(JsonTokenizer.java:532)
at org.glassfish.json.JsonTokenizer.nextToken(JsonTokenizer.java:415)
at org.glassfish.json.JsonParserImpl$NoneContext.getNextEvent(JsonParserImpl.java:222)
at org.glassfish.json.JsonParserImpl$StateIterator.next(JsonParserImpl.java:172)
at org.glassfish.json.JsonParserImpl.next(JsonParserImpl.java:149)
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:101)
at Main.main(Main.java:19)
Has anyone some ideas?
Upvotes: 1
Views: 20293
Reputation: 1332
Get the json response and replace all new lines first before parsing it to object.
response.replaceAll("\r?\n", "");
Sample code using GSON API
String json = "{\"msg\" : \"Hello \n World\"}";
System.out.println(json);
json = json.replaceAll("\r?\n", "");
Map<String, String> map = new Gson().fromJson(json, new TypeToken<Map<String, String>>(){}.getType());
System.out.println("Actual message:" + map.get("msg"));
Output:
{"msg" : " Hello
World"}
Actual message: Hello World
Upvotes: 4