如何com.google.gson.JsonObject在java 中将值设置为null ?通过使用isNull,我当然可以读取一个值是否为null - 但是当我放入null时,它似乎只是忽略它:
JSONObject jsonObj = new JSONObject();
jsonobjToEra.addProperty("sun", Double.parseDouble(val));
jsonobjToEra.addProperty("mon", 22.333);
jsonobjToEra.addProperty("val", null); //ignoring it
Run Code Online (Sandbox Code Playgroud)
请注意我使用的com.google.gson.JsonObject是与类似的问题不同,例如如何在java中使用org.json.JSONObject将值设置为null?在此SO的其他帖子中.
JSON:
[
{
"sun": 1122435343453,
"mon": 1460538600000,
"val": 45.900001525878906
},
{
"sun": 1460538600000,
"mon": 1460538660000,
"val": 45.900001525878906
}
]
Run Code Online (Sandbox Code Playgroud) 我正在使用Java + Groovy脚本。是否可以更改由Groovy类名称(Script1.groovy,Script777.groovy等)生成的值?如果出现异常,很难找到正确的脚本:/
Caused by: org.json.JSONException: JSONObject["value14"] not found.
at org.json.JSONObject.get(JSONObject.java:498)
at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.MethodMetaProperty$GetMethodMetaProperty.getProperty(MethodMetaProperty.java:59)
at org.codehaus.groovy.runtime.callsite.GetEffectivePojoPropertySite.getProperty(GetEffectivePojoPropertySite.java:61)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:227)
at Script4.run(Script4.groovy:23)
at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:346)
... 13 more
Run Code Online (Sandbox Code Playgroud) 下面是我制作JSONObject然后打印出来的方法JSONString.
我正在使用谷歌GSON.
private String generateData(ConcurrentMap<String, Map<Integer, Set<Integer>>> dataTable, int i) {
JsonObject jsonObject = new JsonObject();
Set<Integer> ap = dataTable.get("TEST1").get(i);
Set<Integer> bp = dataTable.get("TEST2").get(i);
jsonObject.addProperty("description", "test data");
jsonObject.addProperty("ap", ap.toString());
jsonObject.addProperty("bp", bp.toString());
System.out.println(jsonObject.toString());
return jsonObject.toString();
}
Run Code Online (Sandbox Code Playgroud)
目前,如果我打印出来, jsonObject.toString()那么它打印出来像这样 -
{"description":"test data","ap":"[0, 1100, 4, 1096]","bp":"[1101, 3, 6, 1098]"}
Run Code Online (Sandbox Code Playgroud)
但这不是我需要的.我想打印出来,如下面没有双引号ap和bp值.
{"description":"test data","ap":[0, 1100, 4, 1096],"bp":[1101, 3, 6, 1098]}
Run Code Online (Sandbox Code Playgroud)
我不知道如何在JSONObject中转义引号?
我有一个无效的json字符串,如下所示,
"{one: 'one', two: 'two'}"
Run Code Online (Sandbox Code Playgroud)
我试图使用JSON.parse将其转换为对象.但是,这不是有效的json字符串.是否有任何函数可以将此无效格式转换为有效的json字符串或直接转换为对象?
我想通过使用volley库{"user_id":12,"answers":{"11":3,"12":4,"13":5}}将以下格式的jsonobject发送到服务器
JSONObject object = new JSONObject();
try {
object.put("user_id", user_id);
JSONObject answers = new JSONObject();
for (int i = 0; i < questions.size(); i++) {
JSONObject answer = new JSONObject();
answer.put(questions.get(i).getId(),questions.get(i).getAnswer());
answers.put("answers", answer);
object.put("answers", answer);
}
} catch (JSONException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
如果我想使用StringRequest,我应该如何使用POST方法将此JsonObject发送到服务器
我试图从URL获取(JSON格式)字符串并将其作为Json对象使用.当我将String转换为JSONObject时,我丢失了UTF-8编码.
这是我用来连接到url并获取字符串的函数:
private static String getUrlContents(String theUrl) {
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch(Exception e) {
e.printStackTrace();
}
return content.toString();
}
Run Code Online (Sandbox Code Playgroud)
当我从服务器获取数据时,以下代码显示正确的字符:
String output = getUrlContents(url);
Log.i("message1", output);
Run Code Online (Sandbox Code Playgroud)
但是当我将输出字符串转换为JSONObject时,波斯字符变成了像这样的问号??????.(messages是JSON中数组的名称)
JSONObject reader = new JSONObject(output);
String messages = new String(reader.getString("messages").getBytes("ISO-8859-1"), "UTF-8");
Log.i("message2", messages);
Run Code Online (Sandbox Code Playgroud) 我目前正在学习一些使用JAVA的android编程.我的老师分享了这段代码,它将使用API,获取其JSON文件,并将其转换为JSONArray文件.然后,他将遍历该JSONArray并将它们放入ArrayList,然后将它们显示在一个活动上.
问题是我正在使用的API会返回一个JSONObject文件,而我不知道如何正确地将其转换为JSONArray.
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONArray jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONArray makeHttpRequest(String url, String method) {
sbParams = new StringBuilder();
if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += …Run Code Online (Sandbox Code Playgroud) 我想模拟一些 JSON(我正在从文件中读取),并将其作为某些 Spring Controller 的结果返回。
文件中当然包含正确的 JSON 数据格式,例如:
{"country":"","city":""...}
Run Code Online (Sandbox Code Playgroud)
我的控制器看起来像:
@RestController
@RequestMapping("/test")
public class TestController {
@Value("classpath:/META-INF/json/test.json")
private Resource testMockup;
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody JSONObject getTest() throws IOException {
JSONObject jsonObject = new JSONObject(FileUtils.readFileToString(testMockup.getFile(), CharEncoding.UTF_8));
return jsonObject;
}
}
Run Code Online (Sandbox Code Playgroud)
读取文件本身等jsonObject本身没有问题,
调试 PoV 是正确的,但是我从浏览器获取HTTP 状态 406。我也试过只返回 String (通过返回jsonObject.toString()),而不是JSONObject. 然而,它会导致编码问题 - 因此来自浏览器的 JSON 不是 JSON 本身(一些额外的斜杠、引号等)。
有什么办法可以从文件中返回 JSON?
我正在尝试将对象添加到Node.js中的一个非常大的JSON文件中(但仅当id与现有对象不匹配时).到目前为止我所拥有的:
示例JSON文件:
[
{
id:123,
text: "some text"
},
{
id:223,
text: "some other text"
}
]
Run Code Online (Sandbox Code Playgroud)
app.js
var fs = require('fs');
var jf = require('jsonfile')
var util = require('util')
var file = 'example.json'
// Example new object
var newThing = {
id: 324,
text: 'more text'
}
// Read the file
jf.readFile(file, function(err, obj) {
// Loop through all the objects in the array
for (i=0;i < obj.length; i++) {
// Check each id against the newThing
if (obj[i].id …Run Code Online (Sandbox Code Playgroud) 我正在使用HttpUrlConnection将一些数据发布到我的服务器这里是函数:
private String register(String myurl) throws IOException {
String resp = null;
try {
JSONObject parameters = new JSONObject();
// parameters.put("jsonArray", ((makeJSON())));
parameters.put("key", "key");//getencryptkey());
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setReadTimeout(10000 /* milliseconds *///);
// conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : …Run Code Online (Sandbox Code Playgroud) jsonobject ×10
java ×6
json ×6
android ×3
gson ×2
javascript ×2
arrays ×1
controller ×1
groovy ×1
groovyshell ×1
node.js ×1
php ×1
post ×1
spring ×1
stringify ×1
utf-8 ×1