1. 程式人生 > >jackson框架解析json

jackson框架解析json

Jackson解析的速度算是同類框架中最快的,同時也是Spring MVC中內建使用的解析方式。

準備工作:

並將jar包新增到libs中

package com.example.jacksontest;

import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtils {
	static ObjectMapper objectMapper;

	public static <T> T readValue(String content, Class<T> valueType) {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}
		try {
			return objectMapper.readValue(content, valueType);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static String toJSon(Object object) {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}
		try {
			return objectMapper.writeValueAsString(object);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
package com.example.jacksontest;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.TypeReference;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.jacksongtest.R;

public class MainActivity extends Activity {

	public static ObjectMapper objectMapper = new ObjectMapper();

	private TextView mBeanTextView;
	private TextView mBeanListTextView;
	private TextView mBeanMapTextView;
	private TextView mBeanMapListTextView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mBeanTextView = (TextView) findViewById(R.id.showBean);
		mBeanListTextView = (TextView) findViewById(R.id.showList);
		mBeanMapTextView = (TextView) findViewById(R.id.showMap);
		mBeanMapListTextView = (TextView) findViewById(R.id.showMapList);

		// 1.讀取Bean型別json
		String resultStr = new String();
		String json = "{\"userName\": \"a\",\"password\":\"c\"}";
		resultStr = JsonUtils.readValue(json, User.class).toString();
		mBeanTextView.setText(resultStr);
		

		// 2.讀取List<Bean>型別json
		json = "[{\"userName\": \"a\",\"password\":\"c\"},{\"userName\": \"b\",\"password\":\"d\"}]";
		User[] users = JsonUtils.readValue(json, User[].class);
		List<User> userList = Arrays.asList(users);
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < userList.size(); i++) {
			result.append(userList.get(i).toString() + "\t");
		}
		mBeanListTextView.setText(result);
		

		// 3.1.讀取Map<T,E>型別json:第一種方法TypeFactory
		json = "{\"A\":{\"userName\": \"a\",\"password\":\"c\"},"
				+ "\"B\":{\"userName\":\"b\",\"password\":\"d\"}}";
		Map<String, User> usersMap = (Map<String, User>) readJsonBeanInMap(
				json, String.class, User.class);
		Set<String> keys = usersMap.keySet();
		result = new StringBuffer();
		for (Iterator<String> it = keys.iterator(); it.hasNext();) {
			result.append(usersMap.get(it.next()).toString() + "\t");
		}
		mBeanMapTextView.setText(result);

		// 3.2.讀取Map<T,E>型別json:第二種方法TypeReference
		readJsonBeanInMap(json);
		

		// 4.讀取List<Map<T,E>>型別json:TypeReference
		json = "[{\"A\":{\"userName\": \"a\",\"password\":\"a\"},\"C\":{\"userName\": \"c\",\"password\":\"c\"}},"
				+ "{\"B\":{\"userName\":\"b\",\"password\":\"b\"}}]";
		readJsonBeanInMapInList(json);

	}

	/**
	 * 讀取Map<-Bean>型別json
	 */
	public void readJsonBeanInMap(String json) {
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			Map<String, User> users = objectMapper.readValue(json,
					new TypeReference<Map<String, User>>() {
					});
			Set<String> keys = users.keySet();
			StringBuffer result = new StringBuffer();
			for (Iterator<String> it = keys.iterator(); it.hasNext();) {
				result.append(users.get(it.next()).toString() + "\t");
			}
			System.out.println(result);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 讀取Map<-Bean>型別json
	 * 
	 * @param <T>
	 * @param <E>
	 */
	public <T, E> Map<T, E> readJsonBeanInMap(String json, Class<T> keyType,
			Class<E> valueType) {
		try {
			Map<T, E> map = objectMapper.readValue(json,
					TypeFactory.mapType(HashMap.class, keyType, valueType));
			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 讀取List<-Map<-String,Bean>>型別json
	 */
	public void readJsonBeanInMapInList(String json) {
		try {
			List<Map<String, User>> users = objectMapper.readValue(json,
					new TypeReference<List<Map<String, User>>>() {
					});
			StringBuffer result = new StringBuffer();
			for (int i = 0; i < users.size(); i++) {
				Map<String, User> tempMap = users.get(i);
				Set<String> keys = tempMap.keySet();
				for (Iterator<String> it = keys.iterator(); it.hasNext();) {
					result.append(tempMap.get(it.next()).toString() + "\t");
				}
			}
			mBeanMapListTextView.setText(result);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
<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"
     >

    <TextView
        android:id="@+id/showBeanTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bean" />
    
    <TextView
        android:id="@+id/showBean"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    
    
    <TextView
        android:id="@+id/showListTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="@string/bean_list" />
    
     <TextView
        android:id="@+id/showList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    
    <TextView
        android:id="@+id/showMapTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="@string/bean_map" />
    
     <TextView
        android:id="@+id/showMap"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    
    <TextView
        android:id="@+id/showMapListTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="@string/bean_map_list" />
    
     <TextView
        android:id="@+id/showMapList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>