2015-01-29 4 views
3

I가 난 내 자바 서버에있는 코드 :- json 데이터를 중첩 json 속성에 삽입하는 방법은 무엇입니까?

JSONArray resultJson = new JSONArray(); 
try{ 
    ConnectToDB(); 
    stmt = conn.prepareStatement(query); 
    m_ResultSet = stmt.executeQuery(); 
    resultJson = FromDBToJSON.toJSON(m_ResultSet); 
    } 

나는이 결과를 얻고있다 : 나는 모든 사용자 데이터를 둘 필요가

id: 1, 
dest_country: "England", 
fname: "Duncan", 
lname: "Hurley", 
address: "xyz" 
}, 
{ 
id: 2, 
dest_country: "England", 
fname: "Duncan", 
lname: "Hurley", 
address: "xyz" 
}, 
{ 
id: 3, 
dest_country: "Israel", 
fname: "Duncan", 
lname: "Hurley", 
address: "xyz" 
}, 
{ 
id: 4, 
dest_country: "USA", 
fname: "Duncan", 
lname: "Hurley", 
address: "xyz" 
}, 

을 (이는 FNAME, LNAME, 주소) 다음과 같이 중첩 된 속성으로 변환합니다.

{ 
    id : 2, 
    dest_country: "England", 
    user: { 
     fname: "Duncan", 
     lname: "Hurley", 
     address: "xyz" 
    } 
} 

어떻게 구현할 수 있습니까?

감사합니다.

답변

0

수업은 다음과 같이 구성되어야 할 것이다 :

class User{ 
    public string fname; 
    public string lname; 
    public string address; 
} 

class ResultType{ 
    public int id; 
    public string dest_country; 
    public User user; 
} 

이것은 당신이 JSON을 구문 분석 할 때 찾고있는 결과를 생성한다. json은 현재 클래스 구조를 기반으로하므로 중첩 된 속성에 포함 할 사용자는 해당 데이터가 들어있는 객체 인 프로퍼티에서 생성되어야합니다.

나중에 다른 방법으로 json 데이터를 재구성하는 것이 좋지만 깔끔하지는 않습니다. 그래서 같이 :

JSONArray resultJson = new JSONArray(); 
try{ 
ConnectToDB(); 
stmt = conn.prepareStatement(query); 
m_ResultSet = stmt.executeQuery(); 
while (m_ResultSet.next()) { 
    JsonObject userObject= Json.createObjectBuilder() 
    .add("fname", m_ResultSet.getString("fname") 
    .add("lname", m_ResultSet.getString("lname") 
    .add("adress", m_ResultSet.getString("adress").build(); 

JsonObject resultJson = Json.createObjectBuilder() 
    .add("id", m_ResultSet.getInt("id")) 
    .add("dest_country", m_ResultSet.getString("dest_country")) 
    .add("user", userObject).build(); 
} 

을 수행해야합니다

result.each(function(){ 
    this.user = { fname: this.fname, lname: this.lname, address: this.address }; 
}); 
+0

여기서 js를 언급하고 있습니까? 서버 측에서이 작업을 수행해야합니다. – Gil404

+0

두 번째 부분은 js이지만 클래스 구조는 Java 클래스를 참조합니다. 서버 측에서 수행해야하는 경우 클래스를 구조화하여 구조에서 데이터를 생성해야하므로 그렇지 않으면 노동 집약적이며 유지 보수가 쉽지 않고 출력을 수정할 재사용이되지 않습니다. – Dhunt

+0

ok, 그렇다면 결과 집합의 모든 열을 각 속성에 매핑해야 함을 의미합니다. 또는 이것을 수행하는 "자동"방법이 있습니까? – Gil404

관련 문제