I want to convert following json string to java arraylist so that i can get hold of id or name inside docs and make changes in java.
{
response{
docs[
{id:#
name:#
}
]
}
}
I want to convert following json string to java arraylist so that i can get hold of id or name inside docs and make changes in java.
{
response{
docs[
{id:#
name:#
}
]
}
}
There are many HTTP client libraries, but given that you're pulling in JSON your best bet is to use the Jersey client library. You need to create a Java object which matches the JSON (in this case, a Response
object which contains a field Docs
which is an array of Data
objects or similar) and tell the Jersey client to expect this as a result. Then you will be able to work with Java objects to output it in whatever form you wish.
*Update
Basic overview of the code. First, set up the Jersey client:
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);
Then create your request:
final WebResource webResource = client.resource("http://mydomain.com/myresource");
At this stage, if you want to fetch your JSON back as a String
you can just call:
final String json = webResource.get(String.class);
But the real benefit of using Jersey over the other HTTP clients is that it will parse the JSON for you so that you don't need to think about it. If you create the following classes:
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
}
then you can change your Jersey client code to:
final DataResponse response = webResource.get(DataResponse.class);
and you can now access the fields in response as per a normal Java object.
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.
}
Actually you want to perform HTTP GET, so take a look on this discussion: How do I do a HTTP GET in Java?