英文:
Return a Single Json object as a String
问题
我正在尝试将单个对象:键-值作为JSON响应传递。如何添加单个JSON对象并将其作为字符串返回:
{
"flag":"true"
}
英文:
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"
}
答案1
得分: 1
你可以尝试下面的代码:
try {
JSONObject jsonObject = new JSONObject("{\"flag\":\"true\"}");
jsonObject.toString();
}catch (JSONException err){
Log.d("Error", err.toString());
}
英文:
You may try below code
try {
JSONObject jsonObject = new JSONObject("{\"flag\":\"true\"}");
jsonObject.toString()
}catch (JSONException err){
Log.d("Error", err.toString());
}
答案2
得分: 1
您可以尝试使用Maven导入Jackson databind依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
// 创建一个用于键值JSON的映射
Map<String, String> obj = new HashMap();
obj.put("flag", "true");
ObjectMapper objectMapper = new ObjectMapper();
// 将对象转换为字符串
String output = objectMapper.writeValueAsString(obj);
return output;
英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论