簡體   English   中英

Json Service中的Java Eclipse問題

[英]Java Eclipse Issues in Json Service

嗨,朋友我第一次嘗試打電話給json,我需要一些幫助

我收到以下回應

“ {,” RestResponse“:{,”消息“:[共找到[249]條記錄。”],“結果”:[{,“名稱”:“阿富汗” ,,“ alpha2_code”:“ AF”, ,“ alpha3_code”:“ AFG”,},{,“ name”:“��landIslands” ,,“ alpha2_code”:“ AX” ,,“ alpha3_code”:“ ALA”,},{,“名稱“:” Albania“,” alpha2_code“:” AL“,” alpha3_code“:” ALB“,},{,”名稱“:”阿爾及利亞“,” alpha2_code“:” DZ“,” alpha2_code“: “ BH”,“ alpha3_code”:“ BHR”,},{,................“

但我需要明智的響應鍵或單獨的項,例如名稱或alpha2_code值等,請大家幫我。 下面是我的完整代碼。

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");

}

}

您可以創建一個與要解析的JSON匹配的類(和子類),然后使用GSON將所有JSON文本轉換為Java對象。

這里有個簡單的例子:

JSON范例

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

我們基於JSON定義我們的類。

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

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

然后我們可以將JSON轉換為Java對象

 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
 }

您也可以執行相反的操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM