2017-02-08 1 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는 사실 함께 할 수있는 뭔가가 생각 실제의 맵의 값의 순서가 보존되는 것이 보증되어 있지 않은 것을 나타냅니다.

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의이 중첩 된 클래스를 사용할 수 있습니다. 이 오브젝트를 다른 곳에 사용하면 엉망이됩니다.

관련 문제