Java Eclipse Issues in Json Service



嗨,朋友们,我第一次尝试打电话给json,我需要一些帮助

我收到以下回复

"{, "RestResponse" : {, "messages" : [ "共找到 [249] 条记录。" ],, "结果" : [ {, "名称" : "阿富汗",, "alpha2_code" : "AF",, "alpha3_code" : "AFG", }, {, "名称" : "ï¿1/2ï¿1/2陆地岛屿",, "alpha2_code" : "AX",, "alpha3_code" : "ALA", }, {, "名称" : "阿尔巴尼亚",, "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);
 }

最新更新