简体   繁体   English

在Java中从String转换为JSONArray或JSONObject

[英]converting from String to JSONArray or JSONObject in Java

I'm trying to use the JSON library to consume twitter information from the get search feature. 我正在尝试使用JSON库来获取来自get search功能的twitter信息。 I'm getting the error: 我收到错误:
A JSONArray text must start with '[' at 1 [character 2 line 1] JSONArray文本必须以'['at 1 [character 2 line 1]开头

So it's basically in the wrong form. 所以它基本上是错误的形式。 Some people are saying this needs to be an object but everytime I call the constructor it says that it can't take a String as input. 有些人说这需要成为一个对象,但每次我调用构造函数时都会说它不能将String作为输入。 How do I get this string into the form of a JSONArray so that I can access it's elements. 如何将此字符串转换为JSONArray的形式,以便我可以访问它的元素。

Here is my code: 这是我的代码:

URL twitterSource = new URL("http://search.twitter.com/search.json?q=google");
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();

IOUtils.copy(twitterSource.openStream(), urlOutputStream);
String urlContents = urlOutputStream.toString();

// parse JSON
System.out.println(urlContents);
JSONArray jsonArray = new JSONArray(urlContents);

// use
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);

    System.out.println(jsonObject.getString("id"));
    System.out.println(jsonObject.getString("text"));               
    System.out.println(jsonObject.getString("created_at"));
}

my print statement shows the string contains: 我的print语句显示字符串包含:

{"completed_in":0.318,"max_id":144850937012428800,"max_id_str":"144850937012428800","next_page":"?page=2.....................

This is a string in the form of a JSON object but it is not actually an object. 这是一个JSON对象形式的字符串,但它实际上不是一个对象。 It's still a string. 它仍然是一个字符串。 I'm printing a String. 我正在打印一个字符串。 HOw can I get this into an Object or better yet a JSONArray so that I can actually access its elements. 我可以把它变成一个Object或者更好的JSONArray,这样我就可以实际访问它的元素了。

那是一个JSON 对象 ,而不是一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM