简体   繁体   中英

read a string in JSON format in JAVA

I want to read a string as a JSON format(it doesn't have to be JSON, but it seems like JSON format) and represent it to a hashMap(key : Keyword, value : COUNT)

for example, assume I have a String.

String s ={"Welcome":1,"Hi":2,"Hello":1,"Jin":1}; 

Then, make it classification.(for Hashmap key --> word, value--> number). final result would be something like as below.

HashMap<String,String> result;

result.get("Jin"); // output : 1
result.get("Hi"); // output : 2

but my codes, it doesn't go with right way.

JSONParser parser = new JSONParser();
        Object obj = parser.parse(s);
        JSONArray array = new JSONArray();
        array.add(obj);

        System.out.println(array.get(0)); //output: {"Welcome":1,"Hi":2,"Hello":1,"Jin":1}

can it be possible with JSON? or should I split them one by one? (such as split them with "," first and ":" ... so on)

Please give me your kind advice.

Try with below code snippet.

public static void main(final String[] args) throws ParseException {
        String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
        JSONParser parser = new JSONParser();
        HashMap<String, Long> obj = (HashMap<String, Long>) parser.parse(s);
        for(String key : obj.keySet()) {
            System.out.println("Key:" + key + " value:" + obj.get(key));
        }
    }

You can use org.json to fulfill your requirement.

Eg

String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
JSONObject result = new JSONObject(s);

System.out.println(result.get("Jin")); // output : 1
System.out.println(result.get("Hi")); // output : 2

Its a json object not an array ...

try this one :

JSONObject jsonObj = new JSONObject(jsonString.toString());

The easiest to achieve this is by using JACKSON parsers.

import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

String s = "{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}";
ObjectMapper mapper = new ObjectMapper();


Map<String, String> map = mapper.readValue(s, new TypeReference<HashMap<String, String>>() {
});

map.forEach((k, v) -> System.out.println("Key is " + k + " value is " + v));

Prints :

Key is Hi value is 2
Key is Hello value is 1
Key is Welcome value is 1
Key is Jin value is 1

Use Google JSON ie gson library(2.6.2) and your problem will be solved.

Please have a look to the following code

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class StackOverFlowQuestionset {

    public static void main(String[] args) {
        String s ="{\"Welcome\":1,\"Hi\":2,\"Hello\":1,\"Jin\":1}"; 

        HashMap<String,String> result=new HashMap<String,String>();

        Gson gson = new Gson();

        JsonElement jsonElement = gson.fromJson(s, JsonElement.class);

        JsonObject jsonObject = jsonElement.getAsJsonObject();

        Set<Entry<String, JsonElement>> jsonEntrySet = jsonObject.entrySet();

        for(Entry<String, JsonElement> entry:jsonEntrySet){
            result.put(entry.getKey(), entry.getValue().toString());
        }

        System.out.println(result.get("Jin"));
        System.out.println(result.get("Welcome"));
        System.out.println(result.get("Hi"));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM