json服务中的javaeclipse问题

wtlkbnrh  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(257)

嗨,朋友们,我第一次尝试调用json,我需要一些帮助
我收到以下答复
“{,”restresponse“{,”messages“:[”找到的记录总数[249],,”result“:[{,”name“:”afghanistan“,”alpha2\u code“:”af“,”alpha3\u code“:”afg“,},{,”name“:”��陆地岛屿“,”alpha2\u code“:”ax“,”alpha3\u code“:”ala“,},{,”name“:”albana“,”alpha2\u code“:”al“,”alpha3\u code“:”alb“,},{,”name“:”algeria“,”alpha2\u code“:”dz“,”alpha2\u code“:”bh“,”alpha3\u code“:”bhr“,},{
但我需要的响应键明智的或单独的项目,如名称或alpha2\u码值等,你可以帮我。下面是我的完整代码。

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

}

}
8nuwlpux

8nuwlpux1#

您可以创建一个类(和子类)来匹配您试图解析的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);
 }

相关问题