2016-02-12 120 views
3

好了,所以我希望得到的輸出是這樣的:如何將Java對象正確地轉換成JSON(嵌套)

{ 
    "id": 460, 
    "position": { 
     "x": 3078, 
     "y": 3251, 
     "z": 0 
    }, 
    "random-walk": true, 
    "walk-radius": 1 
    }, 

但我目前得到的是:

{ 
    "id": 460, 
    "position": "{ 
    "x": 3078, 
    "y": 3251, 
    "z": 0 
    }", 
    "random-walk": true, 
    "walk-radius": 0 
}, 

問題是我試圖轉換爲json的位置對象。 代碼我想:

Path path = Paths.get("./npcs.json"); 
File file = path.toFile(); 
file.getParentFile().setWritable(true); 

if (!file.getParentFile().exists()) { 
    try { 
     file.getParentFile().mkdirs(); 
    } catch (SecurityException e) { 
     System.out.println("Unable to create directory for donator data!"); 
    } 
} 

try (FileWriter writer = new FileWriter(file)) { 

    Gson builder = new GsonBuilder().setPrettyPrinting().create(); 
    JsonObject object = new JsonObject(); 

    Position pos = new Position(mob.absX, mob.absY, mob.heightLevel); 
    object.addProperty("id", mob.npcId); 
    object.addProperty("position", builder.toJson(pos)); 
    object.addProperty("random-walk", mob.randomWalk); 
    object.addProperty("walk-radius", mob.walkingType); 

    writer.write(builder.toJson(object)); 
    writer.close(); 

} catch (Exception e) { 
    System.out.println("Something went wrong with saving for mob !"); 
    e.printStackTrace(); 
} 

有沒有人有關於如何得到第一個結果的線索?所以沒有雙引號。

+1

的toJSON是否會返回一個JSON,而不是對象。 –

+0

@DaveNewton我明白了,你能告訴我如何正確地做到這一點嗎? –

回答

2

使用此

object.add("position", new Gson().toJsonTree(pos));

,而不是

object.addProperty("position", builder.toJson(pos));

結果應該不是這個樣子:

"position": { 
    "x": 10, 
    "y": 50 
    }, 
+0

謝謝,這就是我一直在尋找的! –

0
JSONObject json = new JSONObject(); 
JSONArray addresses = new JSONArray(); 
JSONObject address; 
try 
{ 
    int count = 15; 

    for (int i=0 ; i<count ; i++) 
    { 
     address = new JSONObject(); 
     address.put("Name","Name no." + i); 
     address.put("Country", "Country no." + i); 
     addresses.put(address); 
    } 
    json.put("Addresses", addresses); 
} 
catch (JSONException jse) 
{ 
    out.println("Error during json formatting" + jse.getMessage()); 
} 

我建議使用主要JSON的JSONObject。之後,添加每個組件。對於一個矢量,添加一個json數組。這是一個我用來更好地理解這個問題的簡單例子。

0

您可以使用自己的java對象來做到精確。 Gson使用反射訪問類中的字段,因此您不必手動解析任何內容。

例如你的情況:

import com.google.gson.annotations.SerializedName; 

    public class Walk { 
     private int id; 
     private Position position; 

     @SerializedName("random-walk") 
     private boolean randomWalk; 

     @SerializedName("walk-radius") 
     private int walkRadius; 
    } 
    public class Position { 
     private int x,y,z; 
    } 

然後使用

Gson gson = new Gson(); 
Walk walk = gson.fromJson(yourJson, Walk.class); 
+0

我想將我的java對象寫入json,而不是將我的json轉換爲java對象。謝謝,雖然:) –

+0

是的,你也可以做相反的。只需致電傑森。您可能需要稍微改變您的Java對象,但那將是正確的做法。 –