How to convert a string to JSON object

Asked

Viewed 729 times

0

I get in the @FormParam a text in JSON format, I want to know how to make it a JSON object in Java, so I can manipulate the elements?

@Produces(MediaType.APPLICATION_JSON)
    public String getContadores(@FormParam("Contadores") String Contadores) throws Exception{

        try{


        }catch(Exception e){


        }

    }

1 answer

3

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
}
  • 1

    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?

  • will have to combine the two instructions I passed to the address, turning it into an Array and reading again

  • 1

    @Victorhenrique { Nome : '', Endereco : { Rua : '', Cidade : '' } } is not an array, because arrays are bounded by [ ]. What this string contains is an object, so treat it with JSONObject (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...

  • 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 : '' } }].

  • 1

    @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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.