java怎么读取json格式的数据

java怎么读取json格式的数据,再在前端表现出来,做网页游戏开发的,急用啊,谢谢!

 /** 
 *  
 * @param result JSON字符串 
 * @param name   JSON数组名称 
 * @param fields JSON字符串所包含的字段 
 * @return       返回List<Map<String,Object>>类型的列表,Map<String,Object>对应于 "id":"1"的结构 
 */  
public static List<Map<String, Object>> convertJSON2List(String result,  
        String name, String[] fields) {  
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
    try {  
        JSONArray array = new JSONObject(result).getJSONArray(name);  

        for (int i = 0; i < array.length(); i++) {  
            JSONObject object = (JSONObject) array.opt(i);  
            Map<String, Object> map = new HashMap<String, Object>();  
            for (String str : fields) {  
                map.put(str, object.get(str));  
            }  
            list.add(map);  
        }  
    } catch (JSONException e) {  
        Log.e("error", e.getMessage());  
    }  
    return list;  
}  

做过的一些json数据解析 几种常用的json数据格式解析

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<Person> getPersons(String key,String jsonString){
        List<Person> list = new ArrayList<Person>();
        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<String> getList(String key,String jsonString){
        List<String> list = new ArrayList<String>();
        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<Map<String, Object>> getListMap(String key,String jsonString){
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        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<String, Object> map = new HashMap<String, Object>();
                Iterator<String> 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;
    }

用fastjson,详细讲解参考 https://blog.csdn.net/qq_45978154/article/details/125004445?spm=1001.2014.3001.5501

如果有用Struts框架那就好办了,struts.xml里配置继承json-defual,一般Struts包都有,在action下个方法,一样的返回结果 struts.xml中

<result name="返回字符串" type="json">
  <param name="includeProperties">传出去的值,传出去的值,...</param> 
  </result>

页面异步刷新的写法

用org.开头的json的jar包 里面有OBjectJson 你可以试试

网上有很多专业把json格式数据转换成对象和把对象转成json格式数据的你可以搜下

可以用org.json,挺好用的,参考:http://www.open-open.com/lib/view/open1381566882614.html

单个的json数据用 :JSONObject jsonObject=JSONObject.fromObject(json_str)
数组用 :JSONArray jsonArray = JSONArray.fromObject(json_str);

alt text

用JSONObject或者Gson都可以

这个你可以将json格式的数据转换成其他格式的,百度下应该有的。

这教给后台去处理啊,让他response.write(json数据);你前端读取就行了

使用第三方的JSON库,fastjson、gson、jackson等等,方便快捷。

利用avro .这是jar 包的下载地址:http://avro.apache.org/releases.html

先封装一个json类

public class Json implements java.io.Serializable{
private boolean success = false;
private String message = null;
private Object object = null;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}

用这个方法可以把一个对象转换为json格式,返回前台。
public void writeJson(Object object) {
try {
String json = JSON.toJSONStringWithDateFormat(object, "yyyy-mm-dd HH:mm:ss");
ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
ServletActionContext.getResponse().getWriter().write(json);
ServletActionContext.getResponse().getWriter().flush();
ServletActionContext.getResponse().getWriter().close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

引入阿里巴巴这个类
import com.alibaba.fastjson.JSON;

Bean o = com.alibaba.fastjson.JSON.parseObject(json, Bean.class);


com.google.code.gson
gson
2.2.4

Gson gson = new Gson();
YourBean bean = gson.fromJson(jsonString, YourBean.class);

<br> function getJsonObject(){<br> var url = &quot;&lt;%=path%&gt;/jsonObjectServlet&quot;;<br> new Ajax.Request(<br> url, <br> {<br> method: &quot;get&quot;,<br> onComplete: showObject,<br> asynchronous: true<br> }<br> );<br> }</p> <pre><code>function showObject(result) { // 将json对象转换成json字符串,需要注意的地方: // 使用eval函数的时候,前面使用&#39;(&#39;,后面使用和&#39;)&#39;连接起来 var userObject = eval(&#39;(&#39; + result.responseText + &#39;)&#39;); // {&quot;id&quot;:&quot;1001&quot;,&quot;name&quot;:&quot;p&quot;,&quot;password&quot;:&quot;123&quot;} var userStr = &quot;&lt;table style=&#39;border:1px solid #0000ff;&#39;&gt;&quot;; userStr += &quot;&lt;tr&gt;&lt;th&gt;id&lt;/th&gt;&lt;td&gt;&quot; + userObject.id + &quot;&lt;/td&gt;&lt;/tr&gt;&quot;; userStr += &quot;&lt;tr&gt;&lt;th&gt;name&lt;/th&gt;&lt;td&gt;&quot; + userObject.name + &quot;&lt;/td&gt;&lt;/tr&gt;&quot;; userStr += &quot;&lt;tr&gt;&lt;th&gt;password&lt;/th&gt;&lt;td&gt;&quot; + userObject.password + &quot;&lt;/td&gt;&lt;/tr&gt;&quot;; userStr += &quot;&lt;/table&gt;&quot;; $(&quot;jsonDiv&quot;).innerHTML = userStr; } </code></pre>

import com.alibaba.fastjson.JSON;
导入个包

用jqueryajax function(data){
用eqch eq之类的函数

这个第三方的json库有很多的,jackson,gson,json-lib,flexjson,json-io,genson,jsonij等,都很好使用的,个人比较喜欢json-lib,gson

使用开源的JAR包,解析JSON,可以根据情况选择,使用很方便

json 源于java吧
百度来的:
JSONObject dataJson=new JSONObject("你的Json数据“);
JSONObject response=dataJson.getJSONObject("response");
JSONArray data=response.getJSONArray("data");
JSONObject info=data.getJSONObject(0);
String province=info.getString("province");
String city=info.getString("city");
String district=info.getString("district");
String address=info.getString("address");
System.out.println(province+city+district+address);

不需要读取再转换,直接返回json数据即可,前端js本身就能解析json数据

前端如果是ajax传Json数据到后端的话,
1.可以使用JSON.stringify(obj) 将Json对象转为string传到后端,java后端采用接收string的方式即可
2.后端解析接收到的类似json格式的string后,当作普通字符串直接处理。即split,replace一类的函数。也可以使用一些json解析架包来解析。
基本上就是这个思路,网上搜索一些实例看一下就明白了。

方法很简单,这篇文章说的比较详细 ,http://blog.csdn.net/xueyepiaoling/article/details/5656058

对象的话,比如:"{...}"这种形式,建立JSONObject,如果是:"[{...},{...}...]",建立JSONArray来解析。
更加简单的有谷歌的Gson,用起来方便。

通过GSON工具包,JSONObejct就是一对{} JSONArray就是一对[]

可以用GSON包

Gson gson = new Gson();
response.getWriter().write(gson.toJson(data));

前台接result.data

去找一下JSON包,里面有jsonarray,jsonObject可以用(具体看API吧),[]括起来是一组数据(类似集合),{}括起来是一个数据(类似一个对象),然后每个数据都以键值对(key : value)对应起来。读的话,页面前端可以用jQuery读,建议看看API

ajax 的方式将 json 数据提交后台

推荐谷歌的gson,非常好用。

JSONObject jb = JSONObject.fromObject(s); JSONArray array1 = jb.getJSONArray("1"); //你的s中有1个array(即\"1\"),2个json对象 (即\"2\":{\"3\":4},\"5\":{\"6\":true}}" ) Iterator iter = array1 .iterator(); while (iter.hasNext()) { JSONObject jsobj = iter.next(); String num =jsobj.getString(".."); }

1、使用json-lib
例如:JSONArray jsonArr = JSONArray.fromObject(userinfo);
JSONObject jsonArr = JSONObject .fromObject(userinfo);
2、使用Gson
String sproinfo = new GsonBuilder().serializeNulls().create().toJson(lpro);

引入import net.sf.json.JSONObject; 用JSONObject 进行转换

JSONObject jb = JSONObject.fromObject(s);
JSONArray array1 = jb.getJSONArray("1"); //你的s中有1个array(即\"1\"),2个json对象 (即\"2\":{\"3\":4},\"5\":{\"6\":true}}" )
Iterator iter = array1 .iterator();

while (iter.hasNext()) {

JSONObject jsobj = iter.next(); String num =jsobj.getString(".."); }

java有很多解析json的jar包,如fast-json,gson,java-json。。。。

参考 Java_jackson_bean/map/list与json相互转换

JSONObject json = new JSONObject();用这里的json对象可以进行前后台的信息传递与交互

ezmorph.jar
json-lib-2.2.2-jdk15.jar
json_simple-1.1.jar

commons-beanutils-1.7.jar
commons-collections.jar
commons-lang.jar
commons-logging-1.1.1.jar

数据例子:
s="{\"1\":[{\"2\":\"3\",\"4\":\"5\",\"6\":[\"7\",\"8\"],\"9\":{\"10\":\"11\",\"12\":\"13\"},\"14\":{\"15\":[{\"16\":\"17\"}],\"18\":[{\"19\":\"20\"}]}}],\"2\":{\"3\":4},\"5\":{\"6\":true}}"

首先要了解json数据的书写格式,这是解决问题的第一步。然后要进行数据解析, 当然解析的时候需要和服务器那边变量的书写格式一致。接下来就是解析数据的问题,首先别把他想象的很复杂,其实很简单的,有 几种数据解析的方式。网上很多资料的,静下心来,10分钟就能明白。我没有复制代码,我相信你能搞定的,加油

simplejson 也是个选项, Cassandra用它

以前写的一个用fastjson解析的例子,你可以参考一下
http://blog.csdn.net/houjixin/article/details/39376411

直接Gson,java web开发和手机移动开发在android方向的都是使用这个包的。简单的可以直接利用java自有的jsonobject就可以了。

直接给你个 工具类 我平常用的挺好使的;
package com.uni2uni.publicTools;

import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.codehaus.jackson.map.ObjectMapper;

import antlr.RecognitionException;
import antlr.TokenStreamException;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.model.JSONArray;
import com.sdicons.json.model.JSONValue;
import com.sdicons.json.parser.JSONParser;
import com.uni2uni.framework.http.HttpModel;
import com.uni2uni.framework.http.HttpRequestExecutor;
import com.uni2uni.framework.http.RequestBuilder;
import com.uni2uni.framework.http.ResultData;
import com.uni2uni.framework.serialization.JsonUtil;
import com.uni2uni.springmvc.web.entity.ParamsVO;
import com.uni2uni.springmvc.web.entity.WebResultData;
import com.uuadd.member.sdk.BaseClient;

public class JsonUtilTools {

/**
 * JAVA对象转换成JSON字符串
 * @param obj
 * @return
 * @throws MapperException
 */ 
public static String objectToJsonStr(Object obj) throws MapperException{
    JSONValue jsonValue = JSONMapper.toJSON(obj);  
    String jsonStr = jsonValue.render(false);
    return jsonStr;
}

/**
 * 重载objectToJsonStr方法
 * @param obj 需要转换的JAVA对象
 * @param format 是否格式化
 * @return
 * @throws MapperException
 */
public static String objectToJsonStr(Object obj,boolean format) throws MapperException{
    JSONValue jsonValue = JSONMapper.toJSON(obj);  
    String jsonStr = jsonValue.render(format);
    return jsonStr;
}   

/**
 * JSON字符串转换成JAVA对象
 * @param jsonStr
 * @param cla
 * @return
 * @throws MapperException
 * @throws TokenStreamException
 * @throws RecognitionException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object jsonStrToObject(String jsonStr,Class<?> cla) throws MapperException, TokenStreamException, RecognitionException{
    Object obj = null;
    try{

        JSONParser parser = new JSONParser(new StringReader(jsonStr));    
        JSONValue jsonValue = parser.nextValue();           
        if(jsonValue instanceof com.sdicons.json.model.JSONArray){
            List list = new ArrayList();
            JSONArray jsonArray = (JSONArray) jsonValue;
            for(int i=0;i<jsonArray.size();i++){
                JSONValue jsonObj = jsonArray.get(i);
                Object javaObj = JSONMapper.toJava(jsonObj,cla); 
                list.add(javaObj);
            }
            obj = list;
        }else if(jsonValue instanceof com.sdicons.json.model.JSONObject){
            obj = JSONMapper.toJava(jsonValue,cla); 
        }else{
            obj = jsonValue;
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    return obj; 
}

/**
 * 将JAVA对象转换成JSON字符串
 * @param obj
 * @return
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
@SuppressWarnings("rawtypes")
public static String simpleObjectToJsonStr(Object obj,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{
    if(obj==null){
        return "null";
    }
    String jsonStr = "{";
    Class<?> cla = obj.getClass();
    Field fields[] = cla.getDeclaredFields();
    for (Field field : fields) {
        field.setAccessible(true);
        if(field.getType() == long.class){
            jsonStr += "\""+field.getName()+"\":"+field.getLong(obj)+",";
        }else if(field.getType() == double.class){
            jsonStr += "\""+field.getName()+"\":"+field.getDouble(obj)+",";
        }else if(field.getType() == float.class){
            jsonStr += "\""+field.getName()+"\":"+field.getFloat(obj)+",";
        }else if(field.getType() == int.class){
            jsonStr += "\""+field.getName()+"\":"+field.getInt(obj)+",";
        }else if(field.getType() == boolean.class){
            jsonStr += "\""+field.getName()+"\":"+field.getBoolean(obj)+",";
        }else if(field.getType() == Integer.class||field.getType() == Boolean.class
                ||field.getType() == Double.class||field.getType() == Float.class                   
                ||field.getType() == Long.class){               
            jsonStr += "\""+field.getName()+"\":"+field.get(obj)+",";
        }else if(field.getType() == String.class){
            jsonStr += "\""+field.getName()+"\":\""+field.get(obj)+"\",";
        }else if(field.getType() == List.class){
            String value = simpleListToJsonStr((List<?>)field.get(obj),claList);
            jsonStr += "\""+field.getName()+"\":"+value+",";                
        }else{      
            if(claList!=null&&claList.size()!=0&&claList.contains(field.getType())){
                String value = simpleObjectToJsonStr(field.get(obj),claList);
                jsonStr += "\""+field.getName()+"\":"+value+",";                    
            }else{
                jsonStr += "\""+field.getName()+"\":null,";
            }
        }
    }
    jsonStr = jsonStr.substring(0,jsonStr.length()-1);
    jsonStr += "}";
        return jsonStr;     
}

/**
 * 将JAVA的LIST转换成JSON字符串
 * @param list
 * @return
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
@SuppressWarnings("rawtypes")
public static String simpleListToJsonStr(List<?> list,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{
    if(list==null||list.size()==0){
        return "[]";
    }
    String jsonStr = "[";
    for (Object object : list) {
        jsonStr += simpleObjectToJsonStr(object,claList)+",";
    }
    jsonStr = jsonStr.substring(0,jsonStr.length()-1);
    jsonStr += "]";     
    return jsonStr;
}   

/**
 * 将JAVA的MAP转换成JSON字符串,
 * 只转换第一层数据
 * @param map
 * @return
 */
public static String simpleMapToJsonStr(Map<?,?> map){
    if(map==null||map.isEmpty()){
        return "null";
    }
    String jsonStr = "{";
    Set<?> keySet = map.keySet();
    for (Object key : keySet) {
        jsonStr += "\""+key+"\":\""+map.get(key)+"\",";     
    }
    jsonStr = jsonStr.substring(0,jsonStr.length()-1);
    jsonStr += "}";
    return jsonStr;
}


public static <T> ResultData<T> convert(String body, Class<T> clazz) {
    try {
        ObjectMapper objectMapper = new ObjectMapper();



        WebResultData<T> resultData = objectMapper.readValue(
                body,
                objectMapper.getTypeFactory().constructParametricType(
                        WebResultData.class, clazz));
        return resultData;
    }
    // catch(JsonParseException ex){
    // //TODO:
    // }catch(JsonMappingException ex){
    // //TODO:
    // }catch(IOException ex){
    // //TODO:
    // }
    catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}



public static void main(String args[]){

    HttpModel model = null;
    HttpRequestExecutor executor = HttpRequestExecutor.getClient();

    String data="{\"TypeID\":\"25E92E37-DBCD-44DF-A8E0-699BFC6C3F8D\",\"Count\":\"5\",\"InsertID\":\"admin\",\"InsertName\":\"赵博测试\"}";
    int count=2;
    int type=2;

    String data1="{\"vvtype\":\""+type+"\",\"count\":\""+type+"\"}";
    String data3="{\"vvtype\":\"2\",\"count\":\"5\"}";

    try {
        ParamsVO vo=new ParamsVO();
        vo.setVvtype(2);
        vo.setCount(5);
        model = executor.execute(RequestBuilder
                .postRequest("http://192.168.7.40:8080/vopvip/vipcardpools/GetVopVipCard")
                .withHeader("Content-Type", "application/json")
                .withData(data1).build());//http://cardAPI.uni2uni.com/api/CardService/PayActive 

// model = executor.execute(RequestBuilder
// .postRequest("http://cardAPI.uni2uni.com/api/CardService/PayActive")
// .withHeader("Content-Type", "application/json")
// .withData(data).build());
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println(model.getBody());

    try {
        BaseClient covent=new BaseClient();
        convert(model.getBody(),ParamsVO[].class);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

    //[{"<CardNo>k__BackingField":"8013889000008635","<Pwd>k__BackingField":"587056"},{"<CardNo>k__BackingField":"8013889000008636","<Pwd>k__BackingField":"892766"},{"<CardNo>k__BackingField":"8013889000008637","<Pwd>k__BackingField":"849163"},{"<CardNo>k__BackingField":"8013889000008638","<Pwd>k__BackingField":"324912"},{"<CardNo>k__BackingField":"8013889000008639","<Pwd>k__BackingField":"329956"}]

}

}

楼主,前端的解析我不太清楚,看你需要的是字符串还是对象。后端处理的话我建议你使用alibaba 的fastjson.jar
里面提供了方法
JSON.parseObject(text, clazz) 转换成java对象
JSONArray.parseArray(text, clazz) 转换成java对象类型的数组
JSON.toJSONString(object) 转换成json格式的字符串

里面还有各种其他可用方法

下面是关于json的博客文章,你可以参考一下
http://hi.baidu.com/yangkailin0123/item/b49a9fd46709e5856cce3f53
http://wangcheng2008china.blog.163.com/blog/static/128635503201152435321527/

java中处理json数据使用到的包:
commons-beanutils.jar
commons-collections-3.2.jar
commons-httpclient-3.0.jar
commons-lang-2.5.jar
commons-logging-1.0.jar
ezmorph-1.0.4.jar
json-lib-2.4-jdk15.jar

主要区分json对象和json数组就行了,解析会变的很容易

用json-lib.jar
例子:
Map map = new HashMap();
map.put("a", "123");
JSONObject jsonObj = JSONObject.fromObject(map);
System.out.println(jsonObj.get("a"));

用JS来读,然后传给JSP.

http://58coding.com/article/detail/24673424286679763

如果是spring框架使用Jackson jar包,并且只用ResponseBody注解即可,话说楼主是前端吗?==

可以用单个的json数据用 :JSONObject jsonObject=JSONObject.fromObject(json_str)

可以参考看:http://www.open-open.com/lib/view/open1381566882614.html

/**

  • @param result JSON字符串
  • @param name JSON数组名称
  • @param fields JSON字符串所包含的字段
  • @return 返回List>类型的列表,Map对应于 "id":"1"的结构
    */

    public static List> convertJSON2List(String result,

    String name, String[] fields) {

    List> list = new ArrayList>();

    try {

    JSONArray array = new JSONObject(result).getJSONArray(name);

    for (int i = 0; i < array.length(); i++) {  
        JSONObject object = (JSONObject) array.opt(i);  
        Map<String, Object> map = new HashMap<String, Object>();  
        for (String str : fields) {  
            map.put(str, object.get(str));  
        }  
        list.add(map);  
    }  
    

    } catch (JSONException e) {

    Log.e("error", e.getMessage());

    }

    return list;

    }

用JSONObject对象,想读到json数据,然后用JSONObject对象去解析就好。或者自己写一个解析,json数据格式还是比较规范的。

阿里fastjson包
JSONObject jsonObject=JSONObject.fromObject(json_str)
JSONArray jsonArray = JSONArray.fromObject(json_str);

JSONObject工具转换

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"));

使用fastjson,JSON类中有好多好用的静态方法,根据json的形式去选择相应的方便,还有很多好用的序列化参数,我之前写了一篇关于使用MyBatis TypeHandler 如何从数据库中读取json格式的数据并直接封装到指定对象,欢迎访问:https://blog.csdn.net/qq_38338409/article/details/124227723?spm=1001.2014.3001.5501