当前位置:首页 » 安卓系统 » android对象转json

android对象转json

发布时间: 2024-07-27 09:50:15

‘壹’ 解析json的数据

一则册、 JSON (javaScript Object Notation)一种简单的数据格式,比xml更轻巧。
Json建构于两种结构:
1、“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对孙厅宏象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。 如:
{
“name”:”jackson”,
“age”:100
}

2、值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)如:
{
“students”:
[
{“伏枝name”:”jackson”,“age”:100},
{“name”:”michael”,”age”:51}
]
}
二、java解析JSON步骤
A、服务器端将数据转换成json字符串
首先、服务器端项目要导入json的jar包和json所依赖的jar包至builtPath路径下(这些可以到JSON-lib官网下载:)

然后将数据转为json字符串,核心函数是:
public static String createJsonString(String key, Object value)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
B、客户端将json字符串转换为相应的javaBean
1、客户端获取json字符串(因为android项目中已经集成了json的jar包所以这里无需导入)
public class HttpUtil
{

public static String getJsonContent(String urlStr)
{
try
{// 获取HttpURLConnection连接对象
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
// 设置连接属性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
// 获取相应码
int respCode = httpConn.getResponseCode();
if (respCode == 200)
{
return ConvertStream2Json(httpConn.getInputStream());
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}

private static String ConvertStream2Json(InputStream inputStream)
{
String jsonStr = "";
// ByteArrayOutputStream相当于内存输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// 将输入流转移到内存输出流中
try
{
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, len);
}
// 将内存流转换为字符串
jsonStr = new String(out.toByteArray());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonStr;
}
}
2、获取javaBean
public static Person getPerson(String jsonStr)
{
Person person = new Person();
try
{// 将json字符串转换为json对象
JSONObject jsonObj = new JSONObject(jsonStr);
// 得到指定json key对象的value对象
JSONObject personObj = jsonObj.getJSONObject("person");
// 获取之对象的所有属性
person.setId(personObj.getInt("id"));
person.setName(personObj.getString("name"));
person.setAddress(personObj.getString("address"));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

return person;
}

public static List<Person> getPersons(String jsonStr)
{
List<Person> list = new ArrayList<Person>();

JSONObject jsonObj;
try
{// 将json字符串转换为json对象
jsonObj = new JSONObject(jsonStr);
// 得到指定json key对象的value对象
JSONArray personList = jsonObj.getJSONArray("persons");
// 遍历jsonArray
for (int i = 0; i < personList.length(); i++)
{
// 获取每一个json对象
JSONObject jsonItem = personList.getJSONObject(i);
// 获取每一个json对象的值
Person person = new Person();
person.setId(jsonItem.getInt("id"));
person.setName(jsonItem.getString("name"));
person.setAddress(jsonItem.getString("address"));
list.add(person);
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

return list;
}

‘贰’ android如何将list转化为json

可以通过jsonObject作为中间转换桥梁,先把你的list转换为jsonObject,然后jsonObject toString(),即可转换为json字符串。但是过于复杂的map对象貌似不行,这样你就只有自己写了

‘叁’ android js 交互 能传json对象吗

最近几个项目的测试结果,Android无法主动通过调用
webview.loadUrl("javascript:"+callbackFunction+"('"+data+"')"); 这种方式将jsonobject类型的data传给js,因为js那边得到就是一个string的对象。

与此同时,js主动调用android的对象方式,android也无法返回给js一个jsonobject,需要js做一下转换,例如:

Android 代码:

[java] view plainprint?
WebView mWebView = (WebView) this.findViewById(R.id.webview);
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setPluginsEnabled(true);
settings.setAllowFileAccess(true);

settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);//不加上,会显示白边
String url="file:///android_asset/t.html"; //js代码卸载t.html里
NavigationInstance navigation =new NavigationInstance(this);
mWebView.addJavascriptInterface(navigation, "Navigation");

NavigationInstance里的代码:

[java] view plainprint?
@Override
public JSONObject GetManeuverInfo() {
try{
JSONObject test=new JSONObject();
test.put("maomao", "value");
return test;
//return new JSONObject(bean.ManeuverInfo);
}catch(Exception e){
Log.e(TAG, "",e);
}
return null;
}

t.html里的代码:

[javascript] view plainprint?
function testAPI(el){
console.log("---------testAPI---------");
eval("var obj = "+Navigation.GetManeuverInfo());

alert('typeof:'+typeof(obj));
alert('maomao:'+obj.maomao);
alert('obj:'+obj);
}
如果直接写成 Navigation.GetManeuverInfo.maomao是会提示undefined,因为js那边只得到了一个string对象而已,它不知道maomao是个key。
通过eval将其转化成表达式就可以调用obj.maomao得到value。

在此ps一下ios,貌似人家支持webview很好,js可以直接获取到json对象.

‘肆’ android 怎样将数据以json格式保存在手机文件中

json是一种轻量级数据交换格式,可以包含对象和数组,以下是一个json字符串的示例:
{"key":[{"key1":"value1","key2":value2",...}]}

json只是一种数据交换格式,并不是存储格式,所以只要你正确地组织好json字符串后,跟其他文件是一样存储的;

同时建议你,如果你存储的数据量比较多的话,建议存储在android系统自带的SQLite数据库中,这样操作起数据来更方便简单;如果数据量非常少,只有三五个字段存储,那样使用android的SharedPreferences可能会是更好的选择,希望你根据应用需求适当选用。

‘伍’ android用volley怎么给服务器发送json

1.下载官网的android SDK(本人用的是eclipse)

2.新建一个android项目:

File->new->andriod Application project

7、下面就是具体的使用post和get请求的代码:

A:发送get请求如下:

package com.example.xiaoyuantong;

import java.util.HashMap;

import java.util.Iterator;

import org.json.JSONException;

import org.json.JSONObject;

import android.app.Activity;

import android.os.Bundle;

import android.util.Log;

import android.widget.TextView;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.Response;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.JsonObjectRequest;

import com.android.volley.toolbox.Volley;

/**

* Demo

*/

public class MainActivity extends Activity {

private RequestQueue requestQueue ;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

init();

}

private void init() {

TextView textView = (TextView)findViewById(R.id.textView);

requestQueue = Volley.newRequestQueue(this);

getJson();

textView.setText("hello");

}

private void getJson(){

String url = "http://192.168.20.1:8080/xiaoyuantong/userAction!register.action?pwd='测试'";

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(

Request.Method.GET, url, null,

new Response.Listener<JSONObject>() {

@Override

public void onResponse(JSONObject response) {

//这里可以打印出接受到返回的json

Log.e("bbb", response.toString());

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError arg0) {

// System.out.println("sorry,Error");

Log.e("aaa", arg0.toString());

}

});

requestQueue.add(jsonObjectRequest);

}

}

B:发送post请求如下:

package com.example.xiaoyuantong;

import java.util.HashMap;

import java.util.Map;

import org.json.JSONException;

import org.json.JSONObject;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.Response;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.JsonObjectRequest;

import com.android.volley.toolbox.Volley;

import android.os.Bundle;

import android.app.Activity;

import android.util.Log;

import android.view.Menu;

import android.widget.TextView;

public class PostActivity extends Activity {

private RequestQueue requestQueue ;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_post);

init();

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.post, menu);

return true;

}

private void init() {

TextView textView = (TextView)findViewById(R.id.postView);

requestQueue = Volley.newRequestQueue(this);

getJson();

textView.setText("hellopost");

}

private void getJson(){

String url = "http://192.168.20.1:8080/xiaoyuantong/userAction!reg.action";

JsonObjectRequest jsonObjectRequest ;

JSONObject jsonObject=new JSONObject() ;

try {

jsonObject.put("name", "张三");

jsonObject.put("sex", "女");

} catch (JSONException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

//打印前台向后台要提交的post数据

Log.e("post",jsonObject.toString());

//发送post请求

try{

jsonObjectRequest = new JsonObjectRequest(

Request.Method.POST, url, jsonObject,

new Response.Listener<JSONObject>() {

@Override

public void onResponse(JSONObject response) {

//打印请求后获取的json数据

Log.e("bbb", response.toString());

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError arg0) {

// System.out.println("sorry,Error");

Log.e("aaa", arg0.toString());

}

});

requestQueue.add(jsonObjectRequest);

} catch (Exception e) {

e.printStackTrace();

System.out.println(e + "");

}

requestQueue.start();

}

}

8、在android的logcat里面能查看到打印的请求

(红色的显示的是我在后台请求到数据)

有时候logcat显示不出数据,可能是消息被过滤了,可以在左边点击“减号”删除过滤

在server端,也就是在myeclipse的建立的另一个后台工程里面能获取到请求:


9、后续会补充json数据的解析部分,以及过度到移动云的部分,上面只是c/s模式下的一个简单的基于http的请求应答例子。

‘陆’ android 解析json用那个包里面的方法比较好呢

android 解析json还有用Google出品的Gson比较好,具体步骤为:
1、首先,从 code.google.com/p/google-gson/downloads/list下载GsonAPI:
google-gson-1.7.1-release.zip 把gson-1.7.jar 到libs(项目根目录新建一个libs文件夹)中。 可以使用以下两种方法解析JSON数据,通过获取JsonReader对象解析JSON数据。
代码如下:
String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]";
try{
JsonReader reader = new JsonReader(new StringReader(jsonData));
reader.beginArray();
while(reader.hasNext()){
reader.beginObject();
while(reader.hasNext()){
String tagName = reader.nextName();
if(tagName.equals("username")){
System.out.println(reader.nextString());
}
else if(tagName.equals("userId")){
System.out.println(reader.nextString());
}
}
reader.endObject();
}
reader.endArray();
}
catch(Exception e){
e.printStackTrace();
}
2、使用Gson对象获取User对象数据进行相应的操作:
代码如下:

Type listType = new TypeToken<LinkedList<User>>(){}.getType();
Gson gson = new Gson();
LinkedList<User> users = gson.fromJson(jsonData, listType);
for (Iterator iterator = users.iterator(); iterator.hasNext();) {
User user = (User) iterator.next();
System.out.println(user.getUsername());
System.out.println(user.getUserId());
}
3、如果要处理的JSON字符串只包含一个JSON对象,则可以直接使用fromJson获取一个User对象:
代码如下:

String jsonData = "{\"username\":\"arthinking\",\"userId\":001}";
Gson gson = new Gson();
User user = gson.fromJson(jsonData, User.class);
System.out.println(user.getUsername());
System.out.println(user.getUserId());

热点内容
诺基亚密码忘了打什么电话 发布:2024-09-17 03:27:09 浏览:555
树深度优先算法 发布:2024-09-17 03:26:58 浏览:472
跳转页源码 发布:2024-09-17 03:13:05 浏览:543
html文件上传表单 发布:2024-09-17 03:08:02 浏览:784
聊天软件编程 发布:2024-09-17 03:00:07 浏览:726
linuxoracle安装路径 发布:2024-09-17 01:57:29 浏览:688
两个安卓手机照片怎么同步 发布:2024-09-17 01:51:53 浏览:207
cf编译后没有黑框跳出来 发布:2024-09-17 01:46:54 浏览:249
安卓怎么禁用应用读取列表 发布:2024-09-17 01:46:45 浏览:524
win10设密码在哪里 发布:2024-09-17 01:33:32 浏览:662