【问题标题】:REST and JSON - converting string to JSON arrayREST 和 JSON - 将字符串转换为 JSON 数组
【发布时间】:2012-07-16 11:51:34
【问题描述】:

我是 JSON 和 REST 的新手。我正在使用返回如下字符串的服务器:

[{"username":"Hello","email":"hello@email.com","credits":"100","twitter_username":""},{"username":"Goodbye","email":"goodbye@email.com","credits":"0","twitter_username":""}]

我已经设法在控制台上将它们打印为字符串,但现在我想将它们转换为 JSON 数组。到目前为止,我的代码没有返回任何错误,但我不知道在新 JSON 数组的构造函数中放入什么。我一直在参考一位同事发给我的一段代码,其中构造函数是 new JSONArray(response) 但他从未告诉我“响应”是什么。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import sun.misc.BASE64Encoder;

public class NetClientGet {

    public static void main(String[] args) {

      try {

        URL url = new URL("http://username:password@mobile.crowdedmedia.co.uk/index.php/api/users/get_users/");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        BASE64Encoder enc = new sun.misc.BASE64Encoder();
        String userpassword = "username:password";
        String encoded = enc.encode(userpassword.getBytes());
        conn.setRequestProperty("Authorization", "Basic " + encoded);

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

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

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        JSONArray array = new JSONArray(output);

        for (int i =0; i < array.size(); i++) {
            JSONObject row = array.getJSONObject(i);
            String user = row.getString("username");
            System.out.println(user);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

      }

    }
}

【问题讨论】:

    标签: java json rest


    【解决方案1】:
    • 使用GSON将字符串格式化为JsonArray
    • 然后遍历JsonArray获取值

    代码示例

    String json = "[{\"username\":\"Hello\",\"email\":\"hello@email.com\",\"credits\":\"100\",\"twitter_username\":\"\"},{\"username\":\"Goodbye\",\"email\":\"goodbye@email.com\",\"credits\":\"0\",\"twitter_username\":\"\"}]";
    JsonArray jArray = new JsonParser().parse(json).getAsJsonArray();
    for (int i=0;i<jArray.size();i++) {
        JsonObject jsonObject = jArray.get(i).getAsJsonObject();
        System.out.println(jsonObject.get("username"));
        System.out.println(jsonObject.get("email"));
        System.out.println(jsonObject.get("credits"));
        System.out.println(jsonObject.get("twitter_username"));
        System.out.println("*********");
    }
    

    【讨论】:

    • 谢谢!像魅力一样工作
    • 我确实有一个问题 - 有没有一种方法可以获取 json 字符串而不必像那样硬编码?
    • 在下面的帖子中尝试我给出的代码示例中的 getJson 函数:stackoverflow.com/questions/11471884/…。使用它,您可以从外部服务器下载 json 数据
    【解决方案2】:

    我正在使用 gson 库来操作 json。您可以从here 下载 gson。这是一个非常好的处理 json 的库。 先创建json解析器,它会解析json字符串:

    JsonParser parser = new JsonParser();
    

    现在初始化一个空的 json 数组

    JsonArray jArray = new JsonArray();
    

    现在使用解析器创建 json 数组

    jArray = parser.parse(outputString).getAsJsonArray();
    

    【讨论】:

      【解决方案3】:

      我用过 org.json.simple.JSONObject 和 org.json.simple.JSONArray,我希望 net.sf.json.JSONArray 也一样。

      您应该为 output 输入以下字符串格式 (JSONArray array = new JSONArray(output); )

       {"YOUR_ARRAY_NAME": [{"username":"Hello","email":"hello@email.com","credits":"100","twitter_username":""},{"username":"Goodbye","email":"goodbye@email.com","credits":"0","twitter_username":""}]}
      

      现在这是 JSONArray 的字符串表示。

      【讨论】:

        猜你喜欢
        • 2016-09-24
        • 1970-01-01
        • 2020-04-27
        • 2013-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多