Convert String to Json in Java EE

0

I'm getting a String in a .jsp and would like to convert it to JSON, so I can access the values of it. I've looked for everything, but I could not solve my problem, because I can not access the value of the field. Please, if you can help me, I'll be very grateful, I'm an egg using JSONs.

Below is my code:

// SEND JSON IN FORMAT STRING

    var ItensVenda_String = JSON.stringify(ItensArray);
    var dadosDoForm_String = JSON.stringify(dadosDoForm);

       $.ajax({
            type: "POST",
            url:"http://localhost:8080/ProjBiltiful/cadastrarVenda.jsp",
            data: {data : ItensVenda_String},
            cache: false,
            success: function(){
              alert("Compra registrada com sucesso");
            }
       });

// RECEIVE DATA AS STRING, TRYING TO PASS TO JSON AND ACCESS THE FIELDS

String dados = request.getParameter("data");

//System.out.println(dados);

JSONObject object = new JSONObject(dados.toString()); 
object.get("cbarras");
System.out.println(object.get("cbarras"));
    
asked by anonymous 05.02.2017 / 17:02

1 answer

1

You can use a library that performs parse for you like Jackson dataBind or GSON. Examples Using Jackson

Examples Using GSON

It's basically:

ObjectMapper mapper = new ObjectMapper();
String jsonInString = dados.toString(); // Sua string em JSON
SuaClasse obj = mapper.readValue(jsonInString, SuaClasse.class); //Faz a conversão para seu objeto

After doing the parse you get the properties normally, example

obj.getCodigoBarras(); 
    
06.02.2017 / 19:02