如何将json数据转化为对象?json解析有哪些方法?

在java开发中,我们经常会使用json,json转化出来的数据方便大家阅读以及理解,同时也易于机器解析和生成,那如何将json数据转化为对象?下面来我们就来给大家讲解一下。

如何将json数据转化为对象.jpg

例如:

JSON字符串:

var str1 = '{ "name": "cxh", "sex": "man" }';

JSON对象:

var str2 = { "name": "cxh", "sex": "man" };

JSON字符串转换为JSON对象

要使用上面的str1,必须使用下面的方法先转化为JSON对象:

//由JSON字符串转换为JSON对象
var obj = eval('(' + str + ')');

或者

var obj = str.parseJSON(); //由JSON字符串转换为JSON对象

或者

var obj = JSON.parse(str); //由JSON字符串转换为JSON对象

然后,就可以这样读取:

Alert(obj.name);
Alert(obj.sex);

特别注意:如果obj本来就是一个JSON对象,那么使用eval()函数转换后(哪怕是多次转换)还是JSON对象,但是使用parseJSON()函数处理后会有问题(抛出语法异常)。

json解析有哪些方法?

1、生成json字符串

public static String createJsonString(String key, Object value)
{
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(key, value);
    return jsonObject.toString();
}

2、解析JSON字符串

分为以下三种情况,一个JavaBean,一个List数组,一个嵌套Map的List数组:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import com.android.myjson.domain.Person;
/**
* 完成对json数据的解析
*
*/
public class JsonTools
{
    public static Person getPerson(String key, String jsonString)
        {
            Person person = new Person();
            try
            {
                JSONObject jsonObject = new JSONObject(jsonString);
                JSONObject personObject = jsonObject.getJSONObject("person");
                person.setId(personObject.getInt("id"));
                person.setName(personObject.getString("name"));
                person.setAddress(personObject.getString("address"));
            }
            catch (Exception e)
            {
                // TODO: handle exception }
                return person;
            }
            public static List getPersons(String key, String jsonString)
                {
                    List list = new ArrayList();
                    try
                    {
                        JSONObject jsonObject = new JSONObject(jsonString);
                        // 返回json的数组
                        JSONArray jsonArray = jsonObject.getJSONArray(key);
                        for (int i = 0; i < jsonArray.length(); i++)
                        {
                            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                            Person person = new Person();
                            person.setId(jsonObject2.getInt("id"));
                            person.setName(jsonObject2.getString("name"));
                            person.setAddress(jsonObject2.getString("address"));
                            list.add(person);
                        }
                    }
                    catch (Exception e)
                    {
                        // TODO: handle exception }
                        return list;
                    }
                    public static List getList(String key, String jsonString)
                        {
                            List list = new ArrayList();
                            try
                            {
                                JSONObject jsonObject = new JSONObject(jsonString);
                                JSONArray jsonArray = jsonObject.getJSONArray(key);
                                for (int i = 0; i < jsonArray.length(); i++)
                                {
                                    String msg = jsonArray.getString(i);
                                    list.add(msg);
                                }
                            }
                            catch (Exception e)
                            {
                                // TODO: handle exception }
                                return list;
                            }
                            public static List > listKeyMaps(String key
                                , String jsonString)
                            {
                                List > list = new ArrayList > ();
                                try
                                {
                                    JSONObject jsonObject = new JSONObject(jsonString);
                                    JSONArray jsonArray = jsonObject.getJSONArray(key);
                                    for (int i = 0; i < jsonArray.length(); i++)
                                    {
                                        JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                                        Map map = new HashMap();
                                        Iterator iterator = jsonObject2.keys();
                                        while (iterator.hasNext())
                                        {
                                            String json_key = iterator.next();
                                            Object json_value = jsonObject2.get(json_key);
                                            if (json_value == null)
                                            {
                                                json_value = "";
                                            }
                                            map.put(json_key, json_value);
                                        }
                                        list.add(map);
                                    }
                                }
                                catch (Exception e)
                                {
                                    // TODO: handle exception }
                                    return list;
                                }
                            }

三、JSON解析之GSON

1、生成JSON字符串

import com.google.gson.Gson;
public class JsonUtils
{
    public static String createJsonObject(Object obj)
    {
        Gson gson = new Gson();
        String str = gson.toJson(obj);
        return str;
    }
}

二、解析JSON

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;;
public class GsonTools
{
    public GsonTools()
        {
            // TODO Auto-generated constructor stub }
            /**
            * @param
            * @param jsonString
            * @param cls
            * @return
            */
            public static T getPerson(String jsonString, Class cls)
                {
                    T t = null;
                    try
                    {
                        Gson gson = new Gson();
                        t = gson.fromJson(jsonString, cls);
                    }
                    catch (Exception e)
                    {
                        // TODO: handle exception }
                        return t;
                    }
                    /**
                    * 使用Gson进行解析 List
                    *
                    * @param
                    * @param jsonString
                    * @param cls
                    * @return
                    */
                    public static List getPersons(String jsonString, Class cls)
                    {
                        List list = new ArrayList();
                        try
                        {
                            Gson gson = new Gson();
                            list = gson.fromJson(jsonString, new TypeToken > ()
                            {}.getType());
                        }
                        catch (Exception e)
                        {}
                        return list;
                    }
                    /**
                    * @param jsonString
                    * @return
                    */
                    public static List getList(String jsonString)
                        {
                            List list = new ArrayList();
                            try
                            {
                                Gson gson = new Gson();
                                list = gson.fromJson(jsonString, new TypeToken > ()
                                {}.getType());
                            }
                            catch (Exception e)
                            {
                                // TODO: handle exception }
                                return list;
                            }
                            public static List > listKeyMaps(String jsonString)
                            {
                                List > list = new ArrayList > ();
                                try
                                {
                                    Gson gson = new Gson();
                                    list = gson.fromJson(jsonString
                                        , new TypeToken >> ()
                                        {}.getType());
                                }
                                catch (Exception e)
                                {
                                    // TODO: handle exception }
                                    return list;
                                }
                            }

三、JSON解析之FastJSON

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
public class JsonTool
{
    public static T getPerson(String jsonstring, Class cls)
        {
            T t = null;
            try
            {
                t = JSON.parseObject(jsonstring, cls);
            }
            catch (Exception e)
            {
                // TODO: handle exception }
                return t;
            }
            public static List getPersonList(String jsonstring, Class cls)
                {
                    List list = new ArrayList();
                    try
                    {
                        list = JSON.parseArray(jsonstring, cls);
                    }
                    catch (Exception e)
                    {
                        // TODO: handle exception }
                        return list;
                    }
                    public static List > getPersonListMap1(
                        String jsonstring)
                    {
                        List > list = new ArrayList > ();
                        try
                        {
                            list = JSON.parseObject(jsonstring
                                , new TypeReference >> ()
                                {}.getType());
                        }
                        catch (Exception e)
                        {
                            // TODO: handle exception }
                            return list;
                        }
                    }

在json解析的过程中,我们一定要保证数据的正确性,这样解析出来的数据才是有用的哦!最后大家如果想要了解更多json工具教程知识,敬请关注奇Q工具网。

推荐阅读:

java写游戏用什么引擎?各种java游戏引擎简介

javaidea怎么安装?javaidea安装教程

java关键字能定义成实体类参数吗?java关键字static 怎么用?

推荐内容