Android-封装JSON数据(JSON对象/JSON数组),一般情况下不会在Android端封装JSON的数据,因为封装JSON的数据是在服务器端进行封装了,Android更多的工作是解析(JSON对象/JSON数组)

而且在服务端封装JSON会更加简单灵活:

  例如:JsonTools.createJsonString("persons", list);/JsonTools.createJsonString("person", person);

而这篇博客是讲解在Android-封装JSON数据(JSON对象/JSON数组),只为熟悉JSON数据格式,真实开发中更多的是去解析JSON数据(JSON对象/JSON数组)


注意:⚠ 千万不要jsonObject.toString()
否则会 在前面加" 后面也加" , 都在json数据有问题

package liudeli.mynetwork01;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import java.io.FileOutputStream; public class MainActivity extends Activity { private final String TAG = MainActivity.class.getSimpleName(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} /**
* 封装JSON对象数据
* {
* "name":"李四",
* "age":99,
* "hobby":"爱好是练习截拳道"
* }
*
* @param view
*/
public void pottingJSON1(View view) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "李四");
jsonObject.put("age", 99);
jsonObject.put("hobby", "爱好是练习截拳道");
} catch (JSONException e) {
e.printStackTrace();
} finally {
Log.d(TAG, "jsonObject:" + jsonObject);
saveJSONDataToFile("pottingJSON1", jsonObject);
} } /**
* 封装JSON对象-带Key(student)
* {
* "Student":{
* "name":"李四",
* "age":99,
* "hobby":"爱好是练习截拳道"
* }
* }
*
* @param view
*/
public void pottingJSON2(View view) {
JSONObject jsonObjectALL = null;
try {
// student json 对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "李四");
jsonObject.put("age", 99);
jsonObject.put("hobby", "爱好是练习截拳道"); // 整个最大的 json 对象
jsonObjectALL = new JSONObject(); /**
* 注意:⚠ 千万不要jsonObject.toString()
* 否则会 在前面加" 后面也加" , 都在json数据有问题
*/
jsonObjectALL.put("student", jsonObject); } catch (JSONException e) {
e.printStackTrace();
} finally {
Log.d(TAG, "jsonObjectALL:" + jsonObjectALL);
saveJSONDataToFile("pottingJSON2", jsonObjectALL);
}
} /**
* 封装JSON对象-嵌套对象
* {
* "student":{
* "name":"李四",
* "age":99,
* "hobby":"爱好是练习截拳道",
* "dog":{
* "name":"阿黄",
* "age":"77",
* "sex":"母"
* }
* }
* }
* @param view
*/
public void pottingJSON3(View view) {
JSONObject jsonObjectALL = null;
try {
// dog json 对象
JSONObject dogJSONObject = new JSONObject();
dogJSONObject.put("name", "阿黄");
dogJSONObject.put("age", 77);
dogJSONObject.put("sex", "母"); // student json 对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "李四");
jsonObject.put("age", 99);
jsonObject.put("hobby", "爱好是练习截拳道"); /**
* 注意:⚠ 千万不要dogJSONObject.toString()
* 否则会 在前面加" 后面也加" , 都在json数据有问题
*/
jsonObject.put("dog", dogJSONObject); // 整个最大的 json 对象
jsonObjectALL = new JSONObject(); /**
* 注意:⚠ 千万不要jsonObject.toString()
* 否则会 在前面加" 后面也加" , 都在json数据有问题
*/
jsonObjectALL.put("student", jsonObject); } catch (JSONException e) {
e.printStackTrace();
} finally {
Log.d(TAG, "jsonObjectALL:" + jsonObjectALL);
saveJSONDataToFile("pottingJSON3", jsonObjectALL);
}
} /**
* 封装JSON数组
* [
* {
* "name":"君君",
* "age":89,
* "sex":"男"
* },
* {
* "name":"小君",
* "age":99,
* "sex":"女"
* },
* {
* "name":"大君",
* "age":88,
* "sex":"男"
* }
* ]
*/
public void pottingJSONArray1(View view) {
try {
// 第一个JSON对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "君君");
jsonObject.put("age", 89);
jsonObject.put("sex", "男"); // 第二个JSON对象
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("name", "小君");
jsonObject2.put("age", 99);
jsonObject2.put("sex", "女"); // 第三个JSON对象
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("name", "大君");
jsonObject3.put("age", 88);
jsonObject3.put("sex", "男"); // 定义个JSON数组,把上面的三个JSON对象装进去
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, jsonObject);
jsonArray.put(1, jsonObject2);
jsonArray.put(2, jsonObject3); Log.d(TAG, "jsonArray:" + jsonArray);
saveJSONDataToFile("pottingJSONArray1", jsonArray); } catch (Exception e) {
e.printStackTrace();
}
} /**
* 封装JSON数组-带Key
* {
* "person":[
* {
* "name":"君君",
* "age":89,
* "sex":"男"
* },
* {
* "name":"小君",
* "age":99,
* "sex":"女"
* },
* {
* "name":"大君",
* "age":88,
* "sex":"男"
* }
* ]
* }
* @param view
*/
public void pottingJSONArray2(View view) {
try {
// 第一个JSON对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "君君");
jsonObject.put("age", 89);
jsonObject.put("sex", "男"); // 第二个JSON对象
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("name", "小君");
jsonObject2.put("age", 99);
jsonObject2.put("sex", "女"); // 第三个JSON对象
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("name", "大君");
jsonObject3.put("age", 88);
jsonObject3.put("sex", "男"); // 定义个JSON数组,把上面的三个JSON对象装进去
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, jsonObject);
jsonArray.put(1, jsonObject2);
jsonArray.put(2, jsonObject3); // 整个最大的 json 对象
JSONObject jsonObjectAll = new JSONObject();
// 把上面的JSON数组,装进去
jsonObjectAll.put("person", jsonArray); Log.d(TAG, "jsonObjectAll:" + jsonObjectAll);
saveJSONDataToFile("pottingJSONArray2", jsonObjectAll); } catch (Exception e) {
e.printStackTrace();
}
} /**
* 保存JSON数据到文件
*/
private void saveJSONDataToFile(String fileName, JSONObject jsonData) {
try {
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(jsonData.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 保存JSON数据到文件
*/
private void saveJSONDataToFile(String fileName, JSONArray jsonData) {
try {
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(jsonData.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="封装JSON对象"
android:onClick="pottingJSON1"
android:layout_weight="1"
/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="封装JSON对象-带Key"
android:onClick="pottingJSON2"
android:layout_weight="1"
/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="封装JSON对象-嵌套对象"
android:onClick="pottingJSON3"
android:layout_weight="1"
/> </LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="封装JSON数组"
android:onClick="pottingJSONArray1"
android:layout_weight="1"
/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="封装JSON数组-带Key"
android:onClick="pottingJSONArray2"
android:layout_weight="1"
/> </LinearLayout> </LinearLayout>

结果;

/data/data/liudeli.mynetwork01/files/pottingJSON1

{
"name":"李四",
"age":99,
"hobby":"爱好是练习截拳道"
}

/data/data/liudeli.mynetwork01/files/pottingJSON2

{
"student":{
"name":"李四",
"age":99,
"hobby":"爱好是练习截拳道"
}
}

/data/data/liudeli.mynetwork01/files/pottingJSON3

{
"student":{
"name":"李四",
"age":99,
"hobby":"爱好是练习截拳道",
"dog":{
"name":"阿黄",
"age":77,
"sex":"母"
}
}
}

/data/data/liudeli.mynetwork01/files/pottingJSONArray1

[
{
"name":"君君",
"age":89,
"sex":"男"
},
{
"name":"小君",
"age":99,
"sex":"女"
},
{
"name":"大君",
"age":88,
"sex":"男"
}
]

/data/data/liudeli.mynetwork01/files/pottingJSONArray2

{
"person":[
{
"name":"君君",
"age":89,
"sex":"男"
},
{
"name":"小君",
"age":99,
"sex":"女"
},
{
"name":"大君",
"age":88,
"sex":"男"
}
]
}

Android-封装JSON数据(JSON对象/JSON数组)的更多相关文章

  1. 让复杂Json数据和对象自由转换 --- Gson

    Gson是谷歌用于对Json操作的库,里面有着强大而又方便的功能,最常用的就是 fromJson():将json数据转化为对象: toJson():将对象转化为json数据! 对于普通的json数据使 ...

  2. JS解析json数据并将json字符串转化为数组的实现方法

    json数据在ajax实现异步交互时起到了很重要的作用,他可以返回请求的数据,然后利用客户端的js进行解析,这一点体现出js的强大,本文介绍JS解析json数据并将json字符串转化为数组的实现方法, ...

  3. HttpServletResponse 返回的json数据不是json字符串,而是json对象

    今天在改一个bug 情况: 在spring boot中写了一个类Result ,用来统一封装 各个API响应结果 , 其中重写了toString()方法来返回 json字符串 . 在正常情况下,从其它 ...

  4. js 中 json.stringfy()将对象、数组转换成字符串

    json.stringfy()将对象.数组转换成字符串 var student = new Object(); student.name = "Lanny"; student.ag ...

  5. 如何构建JSON数据,JSON数据的格式,JSON数据的获取

    假设你是用$.getJSON();方法获取JSON数据$.getJSON(url,{"Action":"getStudent"},function(data){ ...

  6. Jquery Ajax和getJSON获取后台普通Json数据和层级Json数据解析

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  7. JS:字符串转成json数据,和json转成字符串方法 iframe获取父级传过来的数据

    字符串转成json数据,和json转成字符串方法 //转为JSON adinfo=JSON.parse(adinfo) //转为字符串 adinfo=JSON.stringify(adinfo) 大概 ...

  8. JSON数据和对象

    在js中像数字类型.字符串类型.布尔类型这些都不能再被拆分,属于基本类型.与之相对有一种复杂类型:对象类型,它是本身由多个其他类型组合而成的. 创建对象有两种方法,一.new Object()创建一个 ...

  9. js声明json数据,打印json数据,遍历json数据,转换json数据为数组

    1.js声明json数据: 2.打印json数据: 3.遍历json数据: 4.转换json数据为数组; //声明JSON var json = {}; json.a = 1; //第一种赋值方式(仿 ...

  10. json数据转为对象,一般在前台把数据传回后端中使用 转https://www.cnblogs.com/zxtceq/p/6610214.html

    public static JArray GetData2JArray(string url, string key) { string jsonData = HttpHelper.HttpGet(u ...

随机推荐

  1. URL的getFile()和getPath()方法的区别(转)

    转自博客:http://blog.csdn.net/l375852247/article/details/7999063 import java.net.MalformedURLException; ...

  2. php错误:Uncaught exception com_exception with message Failed to create COM object

    本文为大家讲解的是php错误:Uncaught exception com_exception with message Failed to create COM object,感兴趣的同学参考下. ...

  3. 根据插件Swipe,结合jQuery封装成的新的jQuery插件

    swipe支持电脑上的自动滑动,也支持手机端的滑动效果.但是每次调用只能支持一个效果或者说一个页面出现n个这样的效果,我们就得调用n次这个插件. 我使用swipe+jQuery使得swip变得方便使用 ...

  4. Vue 安装环境创建项目

    vue 是一个单页面框架,基于模块化组件化的开发模式. 搭建开发环境之前必须要安装node.js,然后安装vue的脚手架工具(命令行工具)win + R 输入npm install  --global ...

  5. M3截止阶段小结

    python知识点总结1.copy模块中深浅拷贝copy() deepcopy()2.__new__ 方法参数    def __new__(cls, *args, **kwargs):        ...

  6. 2017 年 PHP 程序员未来路在何方?

    PHP 从诞生到现在已经有20多年历史,从Web时代兴起到移动互联网退潮,互联网领域各种编程语言和技术层出不穷, Node.js . GO . Python 不断地在挑战 PHP 的地位.这些技术的推 ...

  7. leetcode111

    /** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNo ...

  8. Lazy JSF Primefaces Datatable Pagination

    http://www.javacodegeeks.com/2012/04/lazy-jsf-primefaces-datatable.html

  9. 解决Notepad++ Plugin Manager无法加载插件的方法

    今天正好安装了Notepad++,结果发现Plugin Manager里插件一个也没有,网上对应的方法都没有,最后无意间看到Plugin Manager Settings 里的提示,试了一下居然成功了 ...

  10. Python运维开发基础05-语法基础

    上节作业回顾(讲解+温习90分钟) #!/usr/bin/env python # -*- coding:utf-8 -*- # author:Mr.chen import os,time Tag = ...