Convert JSON to Map

后端 未结 17 2887
天涯浪人
天涯浪人 2020-11-22 10:20

What is the best way to convert a JSON code as this:

{ 
    \"data\" : 
    { 
        \"field1\" : \"value1\", 
        \"field2\" : \"value2\"
    }
}


        
相关标签:
17条回答
  • 2020-11-22 11:14

    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)

    0 讨论(0)
  • 2020-11-22 11:15

    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();
    
    0 讨论(0)
  • 2020-11-22 11:15

    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.

    0 讨论(0)
  • 2020-11-22 11:17

    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}
        }
    }
    
    0 讨论(0)
  • 2020-11-22 11:19

    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));
    
    }
    
    0 讨论(0)
提交回复
热议问题