2016-02-12 134 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对象,但那将是正确的做法。 –