本文将介绍如何从json对象中删除所有null和空字符串值?的详细情况,特别是关于如何从json对象中删除所有null和空字符串值的数据的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面
本文将介绍如何从json对象中删除所有null和空字符串值?的详细情况,特别是关于如何从json对象中删除所有null和空字符串值的数据的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于android – nullpointerexception试图从json字符串中获取json数组或json对象、android – 如何从这个json对象中提取字符串数组?、c#-4.0 – 如何从JSON字符串中删除转义字符、flash – 如何从显示对象中删除所有事件侦听器?的知识。
本文目录一览:- 如何从json对象中删除所有null和空字符串值?(如何从json对象中删除所有null和空字符串值的数据)
- android – nullpointerexception试图从json字符串中获取json数组或json对象
- android – 如何从这个json对象中提取字符串数组?
- c#-4.0 – 如何从JSON字符串中删除转义字符
- flash – 如何从显示对象中删除所有事件侦听器?
如何从json对象中删除所有null和空字符串值?(如何从json对象中删除所有null和空字符串值的数据)
您能告诉我如何从json对象中删除所有null和空字符串值吗?删除密钥时出现错误。
到目前为止,这是我所拥有的,但是不能正常工作:
$.each(sjonObj, function(key, value) { if(value == "" || value == null) { delete sjonObj.key; }});var sjonObj= { "executionMode": "SEQUENTIAL", "coreTEEVersion": "3.3.1.4_RC8", "testSuiteId": "yyy", "testSuiteFormatVersion": "1.0.0.0", "testStatus": "IDLE", "reportPath": "", "startTime": 0, "durationBetweenTestCases": 20, "endTime": 0, "lastExecutedTestCaseId": 0, "repeatCount": 0, "retryCount": 0, "fixedTimeSyncSupported": false, "totalRepeatCount": 0, "totalRetryCount": 0, "summaryReportRequired": "true", "postConditionExecution": "ON_SUCCESS", "testCaseList": [ { "executionMode": "SEQUENTIAL", "commandList": [ ], "testCaseList": [ ], "testStatus": "IDLE", "boundTimeDurationForExecution": 0, "startTime": 0, "endTime": 0, "label": null, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "testCaseId": "a", "summaryReportRequired": "false", "postConditionExecution": "ON_SUCCESS" }, { "executionMode": "SEQUENTIAL", "commandList": [ ], "testCaseList": [ { "executionMode": "SEQUENTIAL", "commandList": [ { "commandParameters": { "serverAddress": "www.ggp.com", "echoRequestCount": "", "sendPacketSize": "", "interval": "", "ttl": "", "addFullDataInReport": "True", "maxRTT": "", "failOnTargetHostUnreachable": "True", "failOnTargetHostUnreachableCount": "", "initialDelay": "", "commandTimeout": "", "testDuration": "" }, "commandName": "Ping", "testStatus": "IDLE", "label": "", "reportFileName": "tc_2-tc_1-cmd_1_Ping", "endTime": 0, "startTime": 0, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "postConditionExecution": "ON_SUCCESS", "detailReportRequired": "true", "summaryReportRequired": "true" } ], "testCaseList": [ ], "testStatus": "IDLE", "boundTimeDurationForExecution": 0, "startTime": 0, "endTime": 0, "label": null, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "testCaseId": "dd", "summaryReportRequired": "false", "postConditionExecution": "ON_SUCCESS" } ], "testStatus": "IDLE", "boundTimeDurationForExecution": 0, "startTime": 0, "endTime": 0, "label": null, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "testCaseId": "b", "summaryReportRequired": "false", "postConditionExecution": "ON_SUCCESS" } ]};$.each(sjonObj, function(key, value) { if(value == "" || value == null) { delete sjonObj.key; }});console.log(sjonObj);<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案1
小编典典您sjonObj.key
实际上是要删除。您需要使用数组访问符号:
delete sjonObj[key];
但是,这也将删除value等于0的地方,因为您没有使用严格的比较。使用===
来代替:
$.each(sjonObj, function(key, value){ if (value === "" || value === null){ delete sjonObj[key]; }});
但是,这只会使对象浅走。要深入地做,可以使用递归:
(function filter(obj) { $.each(obj, function(key, value){ if (value === "" || value === null){ delete obj[key]; } else if (Object.prototype.toString.call(value) === ''[object Object]'') { filter(value); } else if ($.isArray(value)) { $.each(value, function (k,v) { filter(v); }); } });})(sjonObj);var sjonObj = { "executionMode": "SEQUENTIAL", "coreTEEVersion": "3.3.1.4_RC8", "testSuiteId": "yyy", "testSuiteFormatVersion": "1.0.0.0", "testStatus": "IDLE", "reportPath": "", "startTime": 0, "durationBetweenTestCases": 20, "endTime": 0, "lastExecutedTestCaseId": 0, "repeatCount": 0, "retryCount": 0, "fixedTimeSyncSupported": false, "totalRepeatCount": 0, "totalRetryCount": 0, "summaryReportRequired": "true", "postConditionExecution": "ON_SUCCESS", "testCaseList": [ { "executionMode": "SEQUENTIAL", "commandList": [ ], "testCaseList": [ ], "testStatus": "IDLE", "boundTimeDurationForExecution": 0, "startTime": 0, "endTime": 0, "label": null, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "testCaseId": "a", "summaryReportRequired": "false", "postConditionExecution": "ON_SUCCESS" }, { "executionMode": "SEQUENTIAL", "commandList": [ ], "testCaseList": [ { "executionMode": "SEQUENTIAL", "commandList": [ { "commandParameters": { "serverAddress": "www.ggp.com", "echoRequestCount": "", "sendPacketSize": "", "interval": "", "ttl": "", "addFullDataInReport": "True", "maxRTT": "", "failOnTargetHostUnreachable": "True", "failOnTargetHostUnreachableCount": "", "initialDelay": "", "commandTimeout": "", "testDuration": "" }, "commandName": "Ping", "testStatus": "IDLE", "label": "", "reportFileName": "tc_2-tc_1-cmd_1_Ping", "endTime": 0, "startTime": 0, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "postConditionExecution": "ON_SUCCESS", "detailReportRequired": "true", "summaryReportRequired": "true" } ], "testCaseList": [ ], "testStatus": "IDLE", "boundTimeDurationForExecution": 0, "startTime": 0, "endTime": 0, "label": null, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "testCaseId": "dd", "summaryReportRequired": "false", "postConditionExecution": "ON_SUCCESS" } ], "testStatus": "IDLE", "boundTimeDurationForExecution": 0, "startTime": 0, "endTime": 0, "label": null, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "testCaseId": "b", "summaryReportRequired": "false", "postConditionExecution": "ON_SUCCESS" } ]};(function filter(obj) { $.each(obj, function(key, value){ if (value === "" || value === null){ delete obj[key]; } else if (Object.prototype.toString.call(value) === ''[object Object]'') { filter(value); } else if (Array.isArray(value)) { value.forEach(function (el) { filter(el); }); } });})(sjonObj);console.log(sjonObj)<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
请注意,如果您愿意使用lodash /
underscore.js之类的库,则可以_.pick
改用。但是,由于两个库都没有提供深层过滤功能,因此您仍然需要使用递归进行深层过滤。
sjonObj = (function filter(obj) { var filtered = _.pick(obj, function (v) { return v !== '''' && v !== null; }); return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });})(sjonObj);
此变体具有保留原始对象不变的附加优点,但是它确实创建了一个全新的副本,如果您不需要原始对象,效率将会降低。
var sjonObj = { "executionMode": "SEQUENTIAL", "coreTEEVersion": "3.3.1.4_RC8", "testSuiteId": "yyy", "testSuiteFormatVersion": "1.0.0.0", "testStatus": "IDLE", "reportPath": "", "startTime": 0, "durationBetweenTestCases": 20, "endTime": 0, "lastExecutedTestCaseId": 0, "repeatCount": 0, "retryCount": 0, "fixedTimeSyncSupported": false, "totalRepeatCount": 0, "totalRetryCount": 0, "summaryReportRequired": "true", "postConditionExecution": "ON_SUCCESS", "testCaseList": [ { "executionMode": "SEQUENTIAL", "commandList": [ ], "testCaseList": [ ], "testStatus": "IDLE", "boundTimeDurationForExecution": 0, "startTime": 0, "endTime": 0, "label": null, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "testCaseId": "a", "summaryReportRequired": "false", "postConditionExecution": "ON_SUCCESS" }, { "executionMode": "SEQUENTIAL", "commandList": [ ], "testCaseList": [ { "executionMode": "SEQUENTIAL", "commandList": [ { "commandParameters": { "serverAddress": "www.ggp.com", "echoRequestCount": "", "sendPacketSize": "", "interval": "", "ttl": "", "addFullDataInReport": "True", "maxRTT": "", "failOnTargetHostUnreachable": "True", "failOnTargetHostUnreachableCount": "", "initialDelay": "", "commandTimeout": "", "testDuration": "" }, "commandName": "Ping", "testStatus": "IDLE", "label": "", "reportFileName": "tc_2-tc_1-cmd_1_Ping", "endTime": 0, "startTime": 0, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "postConditionExecution": "ON_SUCCESS", "detailReportRequired": "true", "summaryReportRequired": "true" } ], "testCaseList": [ ], "testStatus": "IDLE", "boundTimeDurationForExecution": 0, "startTime": 0, "endTime": 0, "label": null, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "testCaseId": "dd", "summaryReportRequired": "false", "postConditionExecution": "ON_SUCCESS" } ], "testStatus": "IDLE", "boundTimeDurationForExecution": 0, "startTime": 0, "endTime": 0, "label": null, "repeatCount": 0, "retryCount": 0, "totalRepeatCount": 0, "totalRetryCount": 0, "testCaseId": "b", "summaryReportRequired": "false", "postConditionExecution": "ON_SUCCESS" } ]};sjonObj = (function filter(obj) { var filtered = _.pick(obj, function (v) { return v !== '''' && v !== null; }); return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });})(sjonObj);console.log(sjonObj);<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
android – nullpointerexception试图从json字符串中获取json数组或json对象
你好,当我试图从我的jsonString获取一个对象时,我继续得到NPE.我尝试了很多东西甚至改变了我的json一次,但它只是没有用. HTTPResponse工作正常,当我记录“myObject”时,它给出了正确的对象.但是当我试图让对象进入它时,它给了我一个NPE.我测试了json,它是有效的.我也尝试检索一个数组而不是一个对象,但它也提供了一个NPE.有人能告诉我如何解决这个问题.
我做了一个简单的jsontester活动来测试我的json:
public class JSONTester extends Activity { private DefaultHttpClient createHttpClient() { HttpParams my_httpParams = new BasicHttpParams(); httpconnectionParams.setConnectionTimeout(my_httpParams,3000); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80)); ThreadSafeClientConnManager multiThreadedConnectionManager = new ThreadSafeClientConnManager(my_httpParams,registry); DefaultHttpClient httpclient = new DefaultHttpClient(multiThreadedConnectionManager,my_httpParams); return httpclient; } MikeyJSON mJSON; Button mBtnGo; TextView mTxt1; TextView mTxt2; TextView mTxt3; TextView mTxt4; ProgressDialog mProgressDialog; private String lang; private int length; // 0 - 6 (length 7 to length 12) private int wordPos; // 0 - array length @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_jsontester); mTxt1 = (TextView) findViewById(R.id.txt1); mTxt1 = (TextView) findViewById(R.id.txt1); mTxt1 = (TextView) findViewById(R.id.txt1); mTxt1 = (TextView) findViewById(R.id.txt1); mBtnGo = (Button) findViewById(R.id.btnGo); } public boolean isNumeric(String str) { for(int i=0;i<str.length();i++) { if(Character.isDigit(str.charat(i))) { return true; } } return false; } public void testJSON(View view) { if(view==mBtnGo) { mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("loading"); mProgressDialog.show(); new DownloadNewWords().execute(); } } private class DownloadNewWords extends AsyncTask<Void,Void,Void> { int mStatusCode = 0; String mResultString; Exception mConnectionException; @Override protected Void doInBackground(Void... args) { String fetchUrl = "http://www.mikeywebs.nl/json/jsonexample.html"; DefaultHttpClient httpclient = createHttpClient(); HttpGet httpget = new HttpGet(fetchUrl); try { HttpResponse response = httpclient.execute(httpget); StatusLine statusLine = response.getStatusLine(); mStatusCode = statusLine.getStatusCode(); if (mStatusCode == 200){ mResultString = EntityUtils.toString(response.getEntity()); } } catch (ClientProtocolException e) { e.printstacktrace(); mConnectionException = e; } catch (IOException e) { e.printstacktrace(); mConnectionException = e; } return null; } @Override protected void onPostExecute(Void arg) { mProgressDialog.dismiss(); if (mStatusCode == 200){ mJSON = new MikeyJSON(mResultString); lang = "English"; //Integer.parseInt(langu); length = 7; //Integer.parseInt(wordl); wordPos = 0; String getWord = mJSON.getResult(lang,length,wordPos); mTxt4.setText(getWord); } else { Toast.makeText(JSONTester.this,"Gegevens konden niet worden opgehaald. Controleer uw internetverbinding en probeer het opnieuw (" +mConnectionException.toString() + ")",Toast.LENGTH_LONG).show(); mJSON = null; } } } }
我使用的jsonclass是:
public class MikeyJSON { private JSONObject myObject; private JSONArray jsonArray; int i; public MikeyJSON(String jsonString) { Log.i("JSON","jsonString: " + jsonString); try { JSONObject myObject = new JSONObject(jsonString); Log.i("JSON","myObject_Object: " + myObject.toString()); } catch (JSONException e) { // Todo Auto-generated catch block e.printstacktrace(); } } public String getResult(String lang,int length,int wordPos) { String word = "0"; //0 is Nederlands 1 is English int la = 0; if(lang.equals("English")) { la = 1; } //make String length String le = "length" + Integer.toString(length); Log.i("PARSE","get_length: " + le); //the json try { jsonArray = myObject.getJSONArray("galgjejson"); Log.i("JSON","jsonArray: " + jsonArray.toString()); } catch (JSONException e) { // Todo Auto-generated catch block e.printstacktrace(); } return word; } }
这是json:
{ "galgjejson" : [ { "Nederlands" : [ { "length7" : [ { "word" : "android" },{ "word" : "camping" },{ "word" : "koekjes" } ] } ] },{ "English" : [ { "length7" : [ { "word" : "android" },{ "word" : "koekjes" } ] } ] } ] }
这是日志:
03-18 14:06:23.178: I/JSON(6719): myObject_Object: {"Nederlands":[{"length7": [{"word":"android"},{"word":"camping"},{"word":"koekjes"}]}]} 03-18 14:06:23.178: I/PARSE(6719): get_length: length7 03-18 14:06:23.178: D/AndroidRuntime(6719): Shutting down VM 03-18 14:06:23.178: W/dalvikvm(6719): threadid=1: thread exiting with uncaught exception (group=0x40a13300) 03-18 14:06:23.207: E/AndroidRuntime(6719): FATAL EXCEPTION: main 03-18 14:06:23.207: E/AndroidRuntime(6719): java.lang.NullPointerException 03-18 14:06:23.207: E/AndroidRuntime(6719): at me.mikey.my.games.galgjex.MikeyJSON.<init>(MikeyJSON.java:38) 03-18 14:06:23.207: E/AndroidRuntime(6719): at me.mikey.my.games.galgjex.JSONTester$DownloadNewWords.onPostExecute(JSONTester.java:128) 03-18 14:06:23.207: E/AndroidRuntime(6719): at me.mikey.my.games.galgjex.JSONTester$DownloadNewWords.onPostExecute(JSONTester.java:1) 03-18 14:06:23.207: E/AndroidRuntime(6719): at android.os.AsyncTask.finish(AsyncTask.java:631) 03-18 14:06:23.207: E/AndroidRuntime(6719): at android.os.AsyncTask.access$600(AsyncTask.java:177) 03-18 14:06:23.207: E/AndroidRuntime(6719): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) 03-18 14:06:23.207: E/AndroidRuntime(6719): at android.os.Handler.dispatchMessage(Handler.java:99) 03-18 14:06:23.207: E/AndroidRuntime(6719): at android.os.Looper.loop(Looper.java:137) 03-18 14:06:23.207: E/AndroidRuntime(6719): at android.app.ActivityThread.main(ActivityThread.java:4745) 03-18 14:06:23.207: E/AndroidRuntime(6719): at java.lang.reflect.Method.invokeNative(Native Method) 03-18 14:06:23.207: E/AndroidRuntime(6719): at java.lang.reflect.Method.invoke(Method.java:511) 03-18 14:06:23.207: E/AndroidRuntime(6719): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 03-18 14:06:23.207: E/AndroidRuntime(6719): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 03-18 14:06:23.207: E/AndroidRuntime(6719): at dalvik.system.NativeStart.main(Native Method)
哦,第38行是:
jsonArray = myObject.getJSONArray("galgjejson");
解决方法
private JSONObject myObject; private JSONArray jsonArray; int i; public MikeyJSON(String jsonString) { Log.i("JSON","jsonString: " + jsonString); try { myObject = new JSONObject(jsonString); Log.i("JSON","myObject_Object: " + myObject.toString()); } catch (JSONException e) { // Todo Auto-generated catch block e.printstacktrace(); } }
看看那个JSON我很确定你可以使用构造函数中的字符串而不是JSONObject来创建JSONArray.
编辑的例子.
private JSONArray jsonArray; int i; public MikeyJSON(String jsonString) { try { jsonArray = new JSONArray(jsonString); } catch (JSONException e) { // Todo Auto-generated catch block e.printstacktrace(); } }
android – 如何从这个json对象中提取字符串数组?
我正在尝试使用org.json中的类从以下json对象获取可用数字列表
{
"response":true,
"state":1,
"data":
{
"CALLERID":"81101099",
"numbers":
[
"21344111","21772917",
"28511113","29274472",
"29843999","29845591",
"30870001","30870089",
"30870090","30870091"
]
}
}
在从Web服务接收到json对象后,我的第一步是:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
现在,如何保存数字的字符串数组?
解决方法:
采用:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrjson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrjson.length()];
for(int i = 0; i < arrjson.length(); i++)
arr[i] = arrjson.getString(i);
c#-4.0 – 如何从JSON字符串中删除转义字符
"{\"profile\":[{\"name\":\"city\",\"rowCount\":1,\"location\": ............
在我反序列化之前,我尝试使用以下代码删除转义字符:
jsonString = jsonString.Replace(@"\"," ");
但是当我反序列化它时,它会抛出输入字符串不是正确的格式:
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
以下是完整的代码:
public static SearchRootObject obj() { String url = Glare.searchUrl; string jsonString = ""; // Create the web request HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; // Get response var response = request.GetResponse(); Stream receiveStream = response.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. StreamReader readStream = new StreamReader(receiveStream,Encoding.UTF8); jsonString = jsonString + readStream.ReadToEnd(); jsonString = jsonString.Replace(@"\"," "); // A C# object representation of deserialized JSON string SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString); return obj; }
解决方法
我替换了以下代码:
jsonString = jsonString.Replace(@"\"," "); SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString); return obj;
附:
return new JavaScriptSerializer().Deserialize<SearchObj.RootObject>(jsonString);
flash – 如何从显示对象中删除所有事件侦听器?
解决方法
一边不是:displayObject扩展了Eventdispatcher,它已经实现了IEventdispatcher …所以要更精确:你需要重写addEventListener和removeEventListener来跟踪监听器…
一些技术细节:我建议你使用Dictionary来存储处理函数…有点慢的插入,但更快的删除…还有,Dictionary支持弱引用,这在事件处理的情况下是非常重要的.还要记住,useCapture允许添加相同的处理程序两次…
那么祝你好运吧 …
总结
以上是小编为你收集整理的flash – 如何从显示对象中删除所有事件侦听器?全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
今天关于如何从json对象中删除所有null和空字符串值?和如何从json对象中删除所有null和空字符串值的数据的介绍到此结束,谢谢您的阅读,有关android – nullpointerexception试图从json字符串中获取json数组或json对象、android – 如何从这个json对象中提取字符串数组?、c#-4.0 – 如何从JSON字符串中删除转义字符、flash – 如何从显示对象中删除所有事件侦听器?等更多相关知识的信息可以在本站进行查询。
本文标签: