I am relatively new in the mobile development I was working with Mongo consuming an API that local but now I want to know how to deserialize the JSON data that I consume from the API.
Here is how I am working (Localhost), I have managed to show it to me as a String but I would like to serialize it to work it better.
If someone could guide me on how to do it, thank you in advance and a greeting!
public class MainActivity extends AppCompatActivity {
private TextView mResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mResult = (TextView) findViewById(R.id.tv_result);
//hacer solicitud GET
new GetDataTask().execute("http://[IP]:3000/api/product/5c2ae8c084f3ef3ffc369157");
}
class GetDataTask extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
try {
return getData(params[0]);
} catch (IOException ex) {
return "Network error !";
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//configurar la respuesta de datos a textView
mResult.setText("\n"+result);
//cancelar el diálogo de progreso
if (progressDialog != null) {
progressDialog.dismiss();
}
}
private String getData(String urlPath) throws IOException {
StringBuilder result = new StringBuilder();
BufferedReader bufferedReader =null;
try {
//Inicializar y configurar la solicitud, luego conectarse al servidor
URL url = new URL(urlPath);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(10000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/json"); //Establecer encabezado
urlConnection.connect();
//Leer la respuesta de datos del servidor
InputStream inputStream = urlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
return result.toString();
}
}
This is how I managed to show me the JSON:
That's why I want to learn how to deserialize it.