2013-02-07 43 views
0

我想将下面的json字符串转换为java arraylist,以便我可以在文档中获取id或name并在java中进行更改。将json字符串转换为java arraylist(使用jackson)

{ 
response{ 
    docs[ 
    {id:# 
    name:# 
    } 
    ] 
} 
} 
+2

你没有尝试过什么吗?像在谷歌输入您的问题? – home

+0

试试这个[问题](http://stackoverflow.com/questions/1485708/how-do-i-do-a-http-get-in-java) – Oren

+0

可能的重复:http://stackoverflow.com/questions/5769717/how-can-i-get-an-http-response-body-as-a-string-in-java –

回答

1

有很多HTTP客户端库,但因为你是拉动JSON你最好的选择是使用泽西岛客户端库。您需要创建一个与JSON匹配的Java对象(在这种情况下,该对象包含一个Docs对象,该对象是Data对象的数组或类似对象),并通知Jersey客户期望得到此结果。然后,您将能够使用Java对象以任何形式输出它。

* 更新

代码的基本概况。首先,建立了Jersey客户端:

import com.sun.jersey.api.client.Client; 
import com.sun.jersey.api.client.config.DefaultClientConfig; 
import com.sun.jersey.api.client.WebResource; 

.... 


final ClientConfig clientConfig = new DefaultClientConfig(); 
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); 
final Client client = Client.create(clientConfig); 

然后创建您的要求:

final WebResource webResource = client.resource("http://mydomain.com/myresource"); 

在这个阶段,如果你想获取你回JSON作为String你可以拨打:

final String json = webResource.get(String.class); 

但是,将Jersey用于其他HTTP客户端的真正好处在于它会为您解析JSON,因此您不需要考虑它。如果你创建了以下类:

public class DataResponse 
{ 
    private final List<DataDoc> docs; 

    @JsonCreator 
    public DataResponse(@JsonProperty("docs")List<DataDocs> docs) 
    { 
    this.docs = docs; 
    } 

    public List<DataDoc> getDocs() 
    { 
    return this.docs; 
    } 
} 

public class DataDoc 
{ 
    final String id; 
    final String name; 
    // Other fields go here 

    @JsonCreator 
    public DataDoc(@JsonProperty("id") String id, 
       @JsonProperty("name") String name) 
    { 
    this.id = id; 
    this.name = name; 
    } 

    // Getters go here 
} 

那么你就可以改变你的Jersey客户端代码:

final DataResponse response = webResource.get(DataResponse.class); 

,你现在可以访问响应按照正常的Java对象的字段。

+0

您能否在编码语言中解释这一点。我不知道如何在java中做到这一点,我知道我必须这样做,但代码时失败。 – user1964901

+0

添加了一些代码来帮助解释。 – jgm

1
URL url = new URL("webAddress"); 

URLConnection conn = url.openConnection(); 

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

String line = ""; 
ArrayList<String> list = new ArrayList<String>(); 
while ((line = reader.readLine()) != null) { 
     list.add(line); 

    //Perform operation on your data.It will read a line at a time. 

} 
+0

这段代码会做什么? – user1964901

+0

@ user1964901此代码将创建一个URL对象并将webAddress传递给其构造函数。之后,通过调用URL上的openConnection方法创建连接对象。而bufferedReader将缓冲来自指定webAddress的输入。 –

+0

所以在我的情况下,我正在尝试阅读json字符串中docs内的所有内容。所以这段代码将读取整个json文件并将我的数据作为json字符串发回给我? – user1964901