错误意外的字符javax.json

时间:2016-06-21 14:11:05

标签: java json

我正在尝试阅读此JSON代码

{
  "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": []
}

使用我的Java程序:

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();

        }
}

我尝试了不同的东西,但我还没有找到解决方案。它只是给了我错误:

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)

有没有人有想法?

2 个答案:

答案 0 :(得分:3)

获取json响应并在将其解析为object之前先替换所有新行。

response.replaceAll("\r?\n", "");

使用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"));

输出:

{"msg" : " Hello 
 World"}
Actual message: Hello  World

答案 1 :(得分:0)

在我的情况下,错误是由于缺少值或键的引号。在json字符串中 null值不在引号中(例如:&#34; earlyAccessStart&#34;:null)。将它们保留在引号中可以解决问题。

注意:通过valitor like

验证json字符串一次