Question:
Let's say I receive the following content that is stored in a String:
{
"client_id": 1580,
"videos": 4,
"remote_urls": [{
"url": "rtsp://aniceurl.com"
},
{
"url": "rtsp://aniceurl.com"
},
{
"url": "rtsp://aniceurl.com"
},
{
"url": "rtsp://aniceurl.com"
}
],
"action": "start"
}
I recognize the JSON and all, but it's saved in a String, not a JSONObject. I would like to know how I can extract the information from it and store it in variables/arrays, so I can work with this data.
[]'s!
Answer:
you can use google'sGson , it's super simple, just create a class that has exactly the same attributes as the json and parser it, look at the example I made with your json, just using the fromJson method fromJson(meuJson, MinhaClasse.class)
:
CustomerDTO
import java.util.List;
public class ClienteDTO {
private Integer client_id;
private Integer videos;
private List<RemoteUrlDTO> remote_urls;
private String action;
public Integer getClient_id() {
return client_id;
}
public void setCliente_id(Integer cliente_id) {
this.client_id = cliente_id;
}
public Integer getVideos() {
return videos;
}
public void setVideos(Integer videos) {
this.videos = videos;
}
public List<RemoteUrlDTO> getRemote_urls() {
return remote_urls;
}
public void setRemote_urls(List<RemoteUrlDTO> remote_urls) {
this.remote_urls = remote_urls;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
@Override
public String toString() {
return "ClienteDTO [cliente_id=" + client_id + ", videos=" + videos + ", remote_urls=" + remote_urls
+ ", action=" + action + "]";
}
}
RemoteUrlDTO
public class RemoteUrlDTO {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return "RemoteUrlDTO [url=" + url + "]";
}
}
Class for testing and demonstrating GSON:
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
Gson g = new Gson();
String json = "{\n" +
" \"client_id\": 1580,\n" +
" \"videos\": 4,\n" +
" \"remote_urls\": [{\n" +
" \"url\": \"rtsp://aniceurl.com\"\n" +
" },\n" +
" {\n" +
" \"url\": \"rtsp://aniceurl.com\"\n" +
" },\n" +
" {\n" +
" \"url\": \"rtsp://aniceurl.com\"\n" +
" },\n" +
" {\n" +
" \"url\": \"rtsp://aniceurl.com\"\n" +
" }\n" +
" ],\n" +
" \"action\": \"start\"\n" +
"}\n" +
"\n";
ClienteDTO clienteDTO = g.fromJson(json, ClienteDTO.class);
System.out.println(clienteDTO);
}
}
Result after test execution
ClienteDTO [cliente_id=1580, videos=4, remote_urls=[RemoteUrlDTO [url=rtsp://aniceurl.com], RemoteUrlDTO [url=rtsp://aniceurl.com], RemoteUrlDTO [url=rtsp://aniceurl.com], RemoteUrlDTO [url=rtsp://aniceurl.com]], action=start]