2011-03-17 5 views
20

Je poste un AJQ POST jQuery sur un servlet et les données sont sous la forme d'une chaîne JSON. Il est posté avec succès mais du côté de la servlet j'ai besoin de lire ces paires clé-val dans un objet de session et de les stocker. J'ai essayé d'utiliser la classe JSONObject mais je ne suis pas capable de l'obtenir.LIRE une chaîne JSON dans le servlet

Heres l'extrait de code

$(function(){ 
    $.ajax(
    { 
     data: mydata, //mydata={"name":"abc","age":"21"} 
     method:POST, 
     url: ../MyServlet, 
     success: function(response){alert(response); 
    } 
}); 

Du côté Servlet

public doPost(HTTPServletRequest req, HTTPServletResponse res) 
{ 
    HTTPSession session = new Session(false); 
    JSONObject jObj = new JSONObject(); 
    JSONObject newObj = jObj.getJSONObject(request.getParameter("mydata")); 
    Enumeration eNames = newObj.keys(); //gets all the keys 

    while(eNames.hasNextElement()) 
    { 
     // Here I need to retrieve the values of the JSON string 
     // and add it to the session 
    } 
} 
+0

Pourquoi ne pas créer un objet javascript mydata contenant mydata.name, mydata.age? Alors vous pourriez juste tirer les paramètres spécifiques dans votre servlet au lieu de décoder json? – dmcnelis

+0

Je ne peux pas 'cos les clés-vals peuvent varier d'un POST à ​​l'autre – sv1

+0

Vous pourriez, lorsque dans votre fonction décoder le json avec JQuery, fwiw. Ne pas dire que ce devrait être votre solution, mais cela permettrait d'accomplir la même chose. – dmcnelis

Répondre

14

Vous n'êtes pas en train d'analyser le fichier json.

JSONObject jObj = new JSONObject(request.getParameter("mydata")); // this parses the json 
Iterator it = jObj.keys(); //gets all the keys 

while(it.hasNext()) 
{ 
    String key = it.next(); // get key 
    Object o = jObj.get(key); // get value 
    session.putValue(key, o); // store in session 
} 
0

Si vous voulez juste maréchal dans une carte essayez Jackson.

ObjectMapper mapper = new ObjectMapper(); 
... 
Map<String, Object> data = mapper.readValue(request.getParameter("mydata"), Map.class); 
2

Alors, voici mon exemple. J'ai utilisé json.JSONTokener pour tokenize mon String. (JSON-API Java d'ici https://github.com/douglascrockford/JSON-java)

String sJsonString = "{\"name\":\"abc\",\"age\":\"21\"}"; 
// Using JSONTokener to tokenize the String. This will create json Object or json Array 
// depending on the type cast. 
json.JSONObject jsonObject = (json.JSONObject) new json.JSONTokener(sJsonString).nextValue(); 

Iterator iterKey = jsonObject.keys(); // create the iterator for the json object. 
while(iterKey.hasNext()) { 
    String jsonKey = (String)iterKey.next(); //retrieve every key ex: name, age 
    String jsonValue = jsonObject.getString(jsonKey); //use key to retrieve value from 

    //This is a json object and will display the key value pair. 

    System.out.println(jsonKey + " --> " + jsonValue ); 
} 

Sortie:
ans -> 21
nom -> abc

17

si vous utilisez jQuery .ajax(), vous devez lire la HttpRequest flux d'entrée

StringBuilder sb = new StringBuilder(); 
    BufferedReader br = request.getReader(); 
    String str; 
    while((str = br.readLine()) != null){ 
     sb.append(str); 
    }  
    JSONObject jObj = new JSONObject(sb.toString());