简体   繁体   English

Json Service中的Java Eclipse问题

[英]Java Eclipse Issues in Json Service

Hi friends first time i am trying to calling json and I need some help 嗨,朋友我第一次尝试打电话给json,我需要一些帮助

I receive the following response 我收到以下回应

"{, "RestResponse" : {, "messages" : [ "Total [249] records found." ],, "result" : [ {, "name" : "Afghanistan",, "alpha2_code" : "AF",, "alpha3_code" : "AFG", }, {, "name" : "��land Islands",, "alpha2_code" : "AX",, "alpha3_code" : "ALA", }, {, "name" : "Albania",, "alpha2_code" : "AL",, "alpha3_code" : "ALB", }, {, "name" : "Algeria",, "alpha2_code" : "DZ",, "alpha2_code" : "BH",, "alpha3_code" : "BHR", }, {, ................" “ {,” 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”,},{,................“

but i need the response key wise or seperate items like name or alpha2_code values etc can you guy plz help me. 但我需要明智的响应键或单独的项,例如名称或alpha2_code值等,请大家帮我。 below is my complete 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");

}

}

You can create a class (and subclasses) that match the JSON you are trying to parse then using GSON transform all your JSON text into a java object.. 您可以创建一个与要解析的JSON匹配的类(和子类),然后使用GSON将所有JSON文本转换为Java对象。

here a simple example: 这里有个简单的例子:

Example JSON JSON范例

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

We define our classes based on the JSON. 我们基于JSON定义我们的类。

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

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

Then we can convert the JSON to a Java Object 然后我们可以将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
 }

You can also do the opposite: 您也可以执行相反的操作:

  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