Convert from String to Json in Java EE

Asked

Viewed 4,842 times

0

I am receiving a String in a . jsp and would like to convert it to JSON, thus accessing the values of the same. I’ve searched everything, but I couldn’t solve my problem, because I can’t access the value of the field. Please, if you can help me, I would be very grateful, I am egg using Jsons.

Below follows my code:

//SENDING JSON IN STRING FORMAT

    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");
            }
       });

//RECEIVING DATA AS STRING, TRYING TO PASS TO JSON AND ACCESS 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"));

1 answer

1

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

Examples Uitlizando GSON

Basically is:

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 parse Voce takes the properties normally, example

obj.getCodigoBarras(); 
  • I must assume the kind of dados be also SuaClasse?

Browser other questions tagged

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