You can do it like this:
Within the try
will do the treatment.
try {
obj = new JSONObject(jsonResposta);
JSONArray usuarioJArray = (JSONArray) obj.get("result");
obj = (JSONObject) usuarioJArray.get(0);
} catch (JSONException e) {
//erro
}
In the first line of try
I turn into a JSONObject
, if your JSON does not have an array it can already work like this, if it has as my case I turned it into an JSONArray
.
Reading data from a JSONArray
:
try {
JSONArray JArray = (JSONArray) jsonObject.get("produto");
for (int i = 0; i < JArray .length(); i++) {
jsonObject = (JSONObject) produtoJArray.get(i);
value = jsonObject.getDouble(field); //para numeros reais
value = jsonObject.getInt(field); //para numeros inteiros
value = jsonObject.getString(field); //para string
}
catch (JSONException je){
//erro
}
The result will be an array, that is, it will have several JSON texts, because I receive information from users. If I have for example: "{ Name : '', Address : { Street : '', City : '' } } ", it will work that way, taking the value only by setting the field?
– Victor Henrique
will have to combine the two instructions I passed to the address, turning it into an Array and reading again
– GabrielLocalhost
@Victorhenrique
{ Nome : '', Endereco : { Rua : '', Cidade : '' } }
is not an array, because arrays are bounded by[ ]
. What this string contains is an object, so treat it withJSONObject
(this distinction is important because if treating an array as an object or vice versa, it will not work). If you can, please edit the question by placing some examples of strings and how you want to manipulate them. Anyway, I think the most important thing is to first understand the syntax of a JSON, then makes it easier when making the code...– hkotsubo
What I meant to say is that my text that comes with parameter will be as follows: [{ Name : ', Address : { Street : '', City : '' } }] , [{ Name : ', Address : ', { Street : ', City : '' } }] , [{ Name : ', Address : { Street : ', City : '' } }].
– Victor Henrique
@Victorhenrique In this case, the string has several arrays, so create a single
JSONArray
won’t work (if I’m not mistaken, the constructor will just take the first array and ignore the rest). I suggest that you edit the question and put this string there, so the answers can focus on this specific case.– hkotsubo