简体   繁体   中英

Return a Single Json object as a String

I am trying to pass a single object:key-value as a JSON response. How to add a single JSON object and return it as a String:

{

"flag":"true"

}

You may try below code

try {
     JSONObject jsonObject = new JSONObject("{\"flag\":\"true\"}");
jsonObject.toString()
}catch (JSONException err){
     Log.d("Error", err.toString());
}
You can try using Maven Jackson databind dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.5</version>
    </dependency>
   // Create a map for your key value json   
    Map<String,String> obj = new HashMap();
    obj.put("flag","true");
    ObjectMapper objectMapper = new ObjectMapper();
    // Convert object into string
    String output = objectMapper.writeValueAsString(obj);
    return output;

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