What is the best way to convert a JSON code as this:
{
\"data\" :
{
\"field1\" : \"value1\",
\"field2\" : \"value2\"
}
}
I hope you were joking about writing your own parser. :-)
For such a simple mapping, most tools from http://json.org (section java) would work. For one of them (Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:
Map<String,Object> result =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
(where JSON_SOURCE is a File, input stream, reader, or json content String)
I like google gson library.
When you don't know structure of json. You can use
JsonElement root = new JsonParser().parse(jsonString);
and then you can work with json. e.g. how to get "value1" from your gson:
String value1 = root.getAsJsonObject().get("data").getAsJsonObject().get("field1").getAsString();
JSON to Map always gonna be a string/object data type. i haved GSON lib from google.
works very well and JDK 1.5 is the min requirement.
Underscore-java library can convert json string to hash map. I am the maintainer of the project.
Code example:
import com.github.underscore.lodash.U;
import java.util.*;
public class Main {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String json = "{"
+ " \"data\" :"
+ " {"
+ " \"field1\" : \"value1\","
+ " \"field2\" : \"value2\""
+ " }"
+ "}";
Map<String, Object> data = (Map) U.get((Map<String, Object>) U.fromJson(json), "data");
System.out.println(data);
// {field1=value1, field2=value2}
}
}
Use JSON lib E.g. http://www.json.org/java/
// Assume you have a Map<String, String> in JSONObject jdata
@SuppressWarnings("unchecked")
Iterator<String> nameItr = jdata.keys();
Map<String, String> outMap = new HashMap<String, String>();
while(nameItr.hasNext()) {
String name = nameItr.next();
outMap.put(name, jdata.getString(name));
}