2016-06-21 63 views
0

我想讀這個JSON代碼錯誤意外的字符javax.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

獲取json響應並在將其解析爲對象之前先替換所有新行。使用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")); 

輸出

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

示例代碼:

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

由於一次驗證JSON字符串,但我已經找到了解決辦法。我之前已經使用Libre Office打開了JsonData.txt,因此它添加了一些標題。我通過用gedit創建一個新的JsonData.txt來修復它。 – Monocito

0

在我的情況下錯誤是由於缺少值或關鍵引號。在json字符串空值不在引號(例如:「earlyAccessStart」:null)。將它們保留在引號中可以解決問題。

注:通過valitor like