Métodos de almacenamiento JSON Java simples

I have a simple JSON string in my class.

String json = "{'key1':'value1','key2':'value2'}";

And I want create 3 simple methods that will

1. Put value in my JSON string.
2. Get value in my JSON string.
3. Remove value in my JSON string.

Is there any simple library in Java? Or I have to implement it myself?


preguntado el 04 de diciembre de 12 a las 04:12

Hi you can use, json-lib-2.1-jdk1.5.jar or Json.jar for using the JSON methods with Java -

Did you even google "java json library"? -

Is there any method without converting to Map? -

3 Respuestas

Usa Jackson:


Publicación por entregas:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValue(new Simple());

and with POJO like:

public class Simple {
    public int x = 1;
    public int y = 2;

obtendrías algo como:

{"x":1, "y":2}

(except that by default output is not indented: you can enabled indentation using standard Jackson mechanisms)

Deserializing POJOs from JSON:

ObjectMapper mapper = new ObjectMapper();
Simple value = mapper
   .readValue("{\"x\": 1, \"y\": 2}", Simple.class);

Respondido el 05 de diciembre de 12 a las 05:12

Gson can convert Java objects and JSON to each other.

Respondido el 04 de diciembre de 12 a las 04:12

Yes Gson works well. There's also jackson.codehaus.org if Gson doesn't float your boat. - Chico de programación

If using GSON. I need to use MAP? String json = "{'data1':100,'data2':'hello'}"; Gson gson = new Gson(); Map obj = gson.fromJson(json, Map.class); - Eazy

If the object that your are serializing/deserializing is a ParameterizedType (i.e. contains at least one type parameter and may be an array) then you must use the toJson(Object, Type) or fromJson(String, Type) method. See google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/…, java.lang.reflect.Type) - reprogramar

Note that your example json string (above comment) does not correspond to a valid Java Map (with values of boxed primitive types) because the types of the values differ. If the types vary, you should read the json into a custom object rather than a Map. - reprogramar

I did a pretty extensive evaluation of json-java libraries a few months ago, and chose json-smart: http://code.google.com/p/json-smart/

Has been working well.

Respondido el 04 de diciembre de 12 a las 04:12

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.