2017-02-08 126 views
2

我試圖以下列格式顯示JSon文件。但是當我運行我的程序時,它顯示底部的頂部。爲什麼是這樣?我是否正確地做了這件事?請在代碼下面找到輸出和預期輸出的圖片。Json格式顯示錯誤

代碼:

public class Student { 

    public static void main(String[] args) { 

     int a = -7; 
     int b = 7; 
     int k = 103; 
     int order = 109; 
     int px = 60; 
     int py = 76; 
     int qx = 101; 
     int qy = 42; 
     int n = 3; 
     int rx = 2; 
     int ry = 102; 
     int sx = 64; 
     int sy = 17; 

     JSONObject obj = new JSONObject(); 
     obj.put("name", "JEAN-LUC PALMYRE"); 
     obj.put("srn", "120299364"); 


     JSONObject objEcc = new JSONObject(); 
     objEcc.put("a",a); 
     objEcc.put("b",b); 
     objEcc.put("k",k); 
     objEcc.put("order",order); 

     obj.put("ecc", objEcc); 

     JSONObject objModk_add = new JSONObject(); 
     objModk_add.put("x", px); 
     objModk_add.put("y", py); 

     obj.put("p", objModk_add); 

     objModk_add.put("x", qx); 
     objModk_add.put("y", qy); 

     obj.put("q", objModk_add); 

     objModk_add.put("x", rx); 
     objModk_add.put("y", ry); 

     obj.put("r", objModk_add); 

     JSONObject objModk_mul = new JSONObject(); 
     objModk_mul.put("x", px); 
     objModk_mul.put("y", py); 

     obj.put("p", objModk_mul); 


     try (FileWriter file = new FileWriter("Jean-LucPalmyre_120299364_CO3326_cw1.json")) 
     { 

      file.write(obj.toJSONString()); 
      file.flush(); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     System.out.print(obj); 

    } 
} 

輸出:

Output

預期輸出:

Expected output

回答

1

我相信這事做的事實JSONObject是實際使用Map來表示,並且Map中值的順序不保證保存。

0

作爲解決方法,您可以向Student類中添加一種方法,以JSON格式打印或返回其屬性。

事情是這樣的:

public class Student { 

private String name; 
private String srn; 
private Ecc ecc; 
... 

public Student(String name, String srn, Ecc ecc ...) { 
    this.name = name; 
    this.srn = srn; 
    this.ecc = ecc; 
    .... 
} 

@Override 
public String toString() { 
    JSONObject jsonName = new JSONObject(); 
    obj.put("name", name); 
    JSONObject jsonSrn = new JSONObject(); 
    obj.put("srn", srn); 
    ... 

    "{" + 
    jsonName.toJSONString() + 
    "," + 
    jsonSrn.toJSONString() + 
    ... // do the sane with the rest of the properties 
    + 
    "}"  
} 
} 

然後,你可以打印這個樣子。

try (FileWriter file = new FileWriter("JeanLucPalmyre_120299364_CO3326_cw1.json")) 
    { 
     file.write(new Student("MARK", "000001", new Ecc()...)); 
     file.flush(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
+0

謝謝!將嘗試一下 –

0

Pacane是對的。如果您使用例如LinkedHashMap,它會起作用。

例如,這將工作...

private class OwnJsonObj extends JSONObject { 
     OwnJsonObj() { 
      super(new LinkedHashMap()); 
     } 
    } 

您可以使用此嵌套類,而不是JSONObject,它保留秩序。 如果你在其他地方使用這個對象,我不推薦它,它會弄得一團糟。