返回一个作为字符串的单个 JSON 对象。

huangapple go评论91阅读模式
英文:

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

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

huangapple
  • 本文由 发表于 2020年7月26日 22:19:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63101378.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定