2017-10-31 5 views
0

안녕 친구 처음에 내가 JSON을 호출하려고 내가자바 이클립스 문제는 JSON 서비스

나는 다음과 같은 응답을

"{"RestResponse받을 도움이 필요 ": {"메시지 "[총 249 개의 레코드가 발견되었습니다." ] ,, "result": [{ "이름": "아프가 니 스탄", "alpha2_code": "AF",, "alpha3_code": "AFG" }, { "name": "��land Islands",, "alpha2_code": "AX",, "alpha3_code": "ALA",}, { ""name ": "알바니아 ",, "alpha2_code": "AL",, "alpha3_code": "ALB",}, {, "name" : "알제리", "alpha2_code": "DZ", "alpha2_code": "BH",, "alpha3_code": "BHR",}, {, ............ .... "

하지만 응답 키가 필요하거나 이름이나 alpha2_code 값 등의 개별 항목이 필요합니다. plz가 나를 도와 줄 수 있습니다. 아래는 내 완벽한 코드입니다. 여기

package com.group.portal.client.common.actions; 

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.ArrayList; 
import org.apache.turbine.util.RunData; 
import org.json.JSONObject; 
import org.mozilla.javascript.json.JsonParser; 
import antlr.collections.List; 


    public class PaymentProcess extends AjaxAction { 

public void doPerform(RunData data) throws Exception { 
    data.getUser(); 

    JSONObject resultJSON = new JSONObject();  
    String msg = "This is Test Message"; 
    boolean error = false; 
    Object object = null; 


    try { 
    URL url = new URL("http://services.groupkt.com/country/get/all"); 

    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

    conn.setRequestMethod("GET"); 
    conn.setRequestProperty("Accept", "application/json"); 

    if (conn.getResponseCode() != 200) { 
     throw new RuntimeException("Failed : HTTP error code : " 
       + conn.getResponseCode()); 
    } 


    BufferedReader br = new BufferedReader(new InputStreamReader(
      (conn.getInputStream()))); 

    ArrayList<String> response = new ArrayList<String>(); 

    StringBuilder sb = new StringBuilder(); 

     String output=""; 

     while ((output = br.readLine()) != null) { 
      System.out.println(output); 
      response.add(output); 

     } 

     resultJSON.put("msg",response.toArray(new String[0])); 

     conn.disconnect(); 
    } 
    catch (MalformedURLException e) { 

      e.printStackTrace(); 

      } catch (IOException e) { 

      e.printStackTrace(); 

      } 


    data.getResponse().setHeader("Cache-Control", 
      "max-age=0,no-cache,no-store,post-check=0,pre-check=0"); 
    data.getResponse() 
      .setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); 
    data.getTemplateInfo() 
      .setTemp(
    TechnicalResourceProvider.XML_HTTP_REQUEST_RESPONSE_CONTENT_TYPE, 
        "application/json; charset=utf-8"); 
    data.getTemplateInfo().setTemp(
      TechnicalResourceProvider.XML_HTTP_REQUEST_RESPONSE, 
      resultJSON.toString().getBytes("UTF-8")); 
    Log.info(getClass(), 
    "Function doperform of class GetAllBalance finished"); 

} 

} 

답변

0
당신은 자바 객체로 모든 JSON 텍스트를 변환 GSON를 사용하여 다음 구문 분석하려고하는 JSON과 일치하는 클래스 (및 서브 클래스)를 만들 수 있습니다

..

간단한 예 :

예 JSON은

{"players": [ 
     {"firstname": "Mark", "lastname": "Landers"}, 
     {"firstname": "holly", "lastname": "hatton"}, 
     {"firstname": "Benji", "lastname": "price"}], 
    "teamname": "new team"} 

우리는 JSON을 기반으로 우리의 클래스를 정의합니다.

public static void main(String [] args) 
{ 
    Team myTeam = getTeam(); 
    String myTeamJson = new GsonBuilder(). 
           serializeNulls(). 
           create(). 
           toJson(obj); 
} 
:

public class Team { 
    public String teamname; 
    public ArrayList<Player> players; 
} 

public class Player { 
    public String firstname; 
    public String lastname; 
} 

그런 다음 우리는 또한 반대를 할 수있는 자바 객체

public static void main(String [] args) 
{ 
    String myJson = "....."; 
    Team nt = (Team) new GsonBuilder(). 
         serializeNulls(). // serialize null values 
         create().   // create the object 
         fromJson(json, Team.class); // from json and class 
} 

에 JSON 변환 할 수 있습니다