资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

java代码json,java代码例子

JSON 解析(java代码)

import net.sf.json.JSONArray;

创新互联是一家专业提供固镇企业网站建设,专注与网站制作、成都网站制作H5页面制作、小程序制作等业务。10年已为固镇众多企业、政府机构等服务。创新互联专业网站建设公司优惠进行中。

import net.sf.json.JSONObject;

public class Test {

public static void main(String[] args) {

String json = "你的json";

JSONArray array = JSONArray.fromObject(json);

JSONObject object = array.getJSONObject(0);

System.out.println(object.get("pm25"));

System.out.println(object.get("currentCity"));

System.out.println();

array = object.getJSONArray("");

for (Object obj : array) {

JSONObject o = JSONObject.fromObject(obj);

System.out.println(o.get("wind"));

System.out.println(o.get("weather"));

System.out.println(o.get("nightPictureUrl"));

System.out.println(o.get("date"));

System.out.println(o.get("dayPictureUrl"));

System.out.println(o.get("temperature"));

System.out.println();

}

array = object.getJSONArray("index");

for (Object obj : array) {

JSONObject o = JSONObject.fromObject(obj);

System.out.println(o.get("zs"));

System.out.println(o.get("des"));

System.out.println(o.get("tipt"));

System.out.println(o.get("title"));

System.out.println();

}

}

}

java 如何解析JSON

一、JSON(JavaScriptObjectNotation)一种简单的数据格式,比xml更轻巧。Json建构于两种结构:1、“名称/值”对的集合(Acollectionofname/valuepairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hashtable),有键列表(keyedlist),或者关联数组(associativearray)。如:{“name”:”jackson”,“age”:100}2、值的有序列表(Anorderedlistofvalues)。在大部分语言中,它被理解为数组(array)如:{“students”:[{“name”:”jackson”,“age”:100},{“name”:”michael”,”age”:51}]}二、java解析JSON步骤A、服务器端将数据转换成json字符串首先、服务器端项目要导入json的jar包和json所依赖的jar包至builtPath路径下(这些可以到JSON-lib官网下载:)然后将数据转为json字符串,核心函数是:publicstaticStringcreateJsonString(Stringkey,Objectvalue){JSONObjectjsonObject=newJSONObject();jsonObject.put(key,value);returnjsonObject.toString();}B、客户端将json字符串转换为相应的javaBean1、客户端获取json字符串(因为android项目中已经集成了json的jar包所以这里无需导入)publicclassHttpUtil{publicstaticStringgetJsonContent(StringurlStr){try{//获取HttpURLConnection连接对象URLurl=newURL(urlStr);HttpURLConnectionhttpConn=(HttpURLConnection)url.openConnection();//设置连接属性httpConn.setConnectTimeout(3000);httpConn.setDoInput(true);httpConn.setRequestMethod("GET");//获取相应码intrespCode=httpConn.getResponseCode();if(respCode==200){returnConvertStream2Json(httpConn.getInputStream());}}catch(MalformedURLExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}return"";}privatestaticStringConvertStream2Json(InputStreaminputStream){StringjsonStr="";//ByteArrayOutputStream相当于内存输出流ByteArrayOutputStreamout=newByteArrayOutputStream();byte[]buffer=newbyte[1024];intlen=0;//将输入流转移到内存输出流中try{while((len=inputStream.read(buffer,0,buffer.length))!=-1){out.write(buffer,0,len);}//将内存流转换为字符串jsonStr=newString(out.toByteArray());}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}returnjsonStr;}}2、获取javaBeanpublicstaticPersongetPerson(StringjsonStr){Personperson=newPerson();try{//将json字符串转换为json对象JSONObjectjsonObj=newJSONObject(jsonStr);//得到指定jsonkey对象的value对象JSONObjectpersonObj=jsonObj.getJSONObject("person");//获取之对象的所有属性person.setId(personObj.getInt("id"));person.setName(personObj.getString("name"));person.setAddress(personObj.getString("address"));}catch(JSONExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}returnperson;}publicstaticListgetPersons(StringjsonStr){Listlist=newArrayList();JSONObjectjsonObj;try{//将json字符串转换为json对象jsonObj=newJSONObject(jsonStr);//得到指定jsonkey对象的value对象JSONArraypersonList=jsonObj.getJSONArray("persons");//遍历jsonArrayfor(inti=0;i

java中把json怎么转换成数组?

使用原生的解析:

String json = "...";

//遍历数组里的值,得到每个独立的对象,然后获取对应的值设置到声明好的对象中,最终创建对象完成后添加到集合中,如我自己代码里的片段:

for (int j = 0; j array.length(); j++) {

obj = array.getJSONObject(j);

Data data = new Data();

mDataList.add(data);

}

数组声明

在数组的声明格式里,“数据类型”是声明数组元素的数据类型,可以是java语言中任意的数据类型,包括简单类型和结构类型。“数组名”是用来统一这些相同数据类型的名称,其命名规则和变量的命名规则相同。

数组声明之后,接下来便是要分配数组所需要的内存,这时必须用运算符new,其中“个数”是告诉编译器,所声明的数组要存放多少个元素,所以new运算符是通知编译器根据括号里的个数,在内存中分配一块空间供该数组使用。利用new运算符为数组元素分配内存空间的方式称为动态分配方式。

以上内容参考:百度百科-数组

Java的json反序列化:Java数据类可以和json数据结构不一致吗?

由于时间关系我也没有写全,这里提供一个思路吧。代码如下:

Account.java:

@Data

public class Account {

private int id;

private String name;

// @PowerfulAnnotation注解是我臆想的

@PowerfulAnnotation("token.id")

private String tokenId;

@PowerfulAnnotation("token.key")

private String key;

}

PowerfulAnnotation.java:

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface PowerfulAnnotation {

String value() default "";

}

测试类Main.java:

public class Main {

public static void main(String[] args) throws Exception {

Account account = new Account();

String ori = "{\n" +

"\"id\": 11111,\n" +

"\"name\": \"小李\",\n" +

"\"token\": {\n" +

"\"id\": 22222222,\n" +

"\"key\": \"ddddddddd\"\n" +

"}\n" +

"}";

Gson gson = new Gson();

//字符串json转JsonObject

JsonObject jsonObject = gson.fromJson(ori, JsonObject.class);

//反射获取目标对象属性

for (Field field : account.getClass().getDeclaredFields()) {

String fieldName = field.getName();

Class fieldClass = field.getType();

System.out.print("当前field名:[" + fieldName + "],");

System.out.println("当前field类型:[" + fieldClass + "]");

Annotation annotation = field.getDeclaredAnnotation(PowerfulAnnotation.class);

//检查是否有PowerfulAnnotation注解

if (annotation != null) {

PowerfulAnnotation powerful = (PowerfulAnnotation) annotation;

String powerfulValue = powerful.value();

System.out.println("发现PowerfulAnnotation注解,值为:[" + powerfulValue + "]");

String[] tmp = powerfulValue.split("\\.");

//声明一个临时JsonObject,将用于获取下一层json对象

JsonObject tmpJson = jsonObject;

for (int i = 0; i tmp.length; i++) {

//目标值是在powerfulValue的最后一个字段,例如powerfulValue为token.id的话,目标的值就是id,所以先获取token这个jsonObject,并赋值给临时tmpJson

if (i != tmp.length - 1) {

tmpJson = jsonObject.get(tmp[i]).getAsJsonObject();

} else {

//到达powerfulValue的最后一个字段,检查其类型,并赋值给目标对象

Object value = checkFieldType(tmpJson, tmp[i], fieldClass);

//从目标对象中获取目标属性

Field targetField = account.getClass().getDeclaredField(field.getName());

targetField.setAccessible(true);//解除私有限制

System.out.println("将[" + powerfulValue + "]的值[" + value + "]赋给目标对象的[" + fieldName + "]");

//将值赋值给目标属性

targetField.set(account, value);

}

}

}

//属性上没有PowerfulAnnotation注解

else {

//检查当前属性的类型

Object value = checkFieldType(jsonObject, fieldName, fieldClass);

//从目标对象中获取目标属性

Field targetField = account.getClass().getDeclaredField(field.getName());

targetField.setAccessible(true);//解除私有限制

System.out.println("直接将值[" + value + "]赋给目标对象的[" + fieldName + "]");

//将值赋值给目标属性

targetField.set(account, value);

}

System.out.println("*********************************************\n");

}

System.out.println("目标对象最终值:" + account);

}

/**

* 检查当前属性的类型

* (这里由于时间关系,我没有写全,只检查了String、int、boolean类型,全类型应包括boolean、char、byte、short、int、long、float、double,你有时间自己补充一下)

*

* 如果发现当前属性是一个对象,那么应该将JsonObject转换成对应的对象再返回(由于时间关系,这里我也没有试过,总之思路是这样)

*/

private static Object checkFieldType(JsonObject field, String fieldName, Class fieldClass) {

if (fieldClass == String.class) {

return field.get(fieldName).getAsString();

}

if (fieldClass == int.class) {

return field.get(fieldName).getAsInt();

}

if (fieldClass == boolean.class) {

return field.get(fieldName).getAsBoolean();

}

return new Gson().fromJson(field.get(fieldName), fieldClass);

}

}

代码还没写完,主要集中在没有对JsonArray进行处理,当json串里包含数组时会报错,另外一些没写完的我在注释里写了点,你可以参照一下。整体思路还是利用java反射机制进行。

以上代码运行结果:

求java合并json数据的代码

我想了一下,但是得有一个前提,就是第一个json数组的size必须和第二个json数组的size相同,并且一一对应,否则将造成数组溢出。

如果是基于上面这个前提,那么实现的方法就简单了。

操作json对象,其实标准的方法是将实体类转换成json后再操作,我这里的话为了便捷直接使用谷歌的Gson来创建JsonObject了,其他的json依赖还有阿里巴巴的FastJson等等,看你平时用什么习惯。

引入Gson依赖:

dependency

groupIdcom.google.code.gson/groupId

artifactIdgson/artifactId

version2.8.0/version

/dependency

实现代码:

public class Main {

public static void main(String[] args) {

JsonArray jsonArray1 = new JsonArray();

JsonObject json11 = new JsonObject();

json11.addProperty("数据1", "0000");

json11.addProperty("数据2", "1111");

JsonObject json12 = new JsonObject();

json12.addProperty("数据1", "0000");

json12.addProperty("数据2", "1111");

JsonObject json13 = new JsonObject();

json13.addProperty("数据1", "0000");

json13.addProperty("数据2", "1111");

jsonArray1.add(json11);

jsonArray1.add(json12);

jsonArray1.add(json13);

System.out.println(jsonArray1);

JsonArray jsonArray2 = new JsonArray();

JsonObject json21 = new JsonObject();

json21.addProperty("数据3", "6666");

JsonObject json22 = new JsonObject();

json22.addProperty("数据3", "6666");

JsonObject json23 = new JsonObject();

json23.addProperty("数据3", "6666");

jsonArray2.add(json21);

jsonArray2.add(json22);

jsonArray2.add(json23);

System.out.println(jsonArray2);

//遍历json数组,按位取出对象

for (int i = 0; i jsonArray1.size(); i++) {

JsonObject json1 = jsonArray1.get(i).getAsJsonObject();

JsonObject json3 = jsonArray2.get(i).getAsJsonObject();

//遍历数据3内容,通过Entry获取数据3的key和value,并合并到数据1中

for (Map.EntryString, JsonElement item : json3.entrySet()) {

json1.addProperty(item.getKey(), item.getValue().getAsString());

}

}

System.out.println(jsonArray1);

}

}

整体思路为:遍历两个json数组,按位进行合并操作。合并时,遍历数据3的jsonObject,获取其key和value,并将其合并到数据1中即可。

运行结果:

java中json怎么运用?

json一般都是配合ajax一起使用的 我做做过的小例子 粘给你 你可以研究一下

js部分

//获取卡的金额

function get_money(){

var str=document.getElementById("pk_card_type").value;

//alert(str);

var url = '/member_h.do';

var pars = 'method=getMoney';

pars+='pk_card_type='+str;

var ajax = new Ajax.Request(

url,

{method:'post',parameters:pars,onComplete:show_money}

);

}

//回调函数 写入卡的金额

function show_money(dataResponse)

{

var data = eval('(' + dataResponse.responseText + ')');

var price=0;

price=data.price;

var collection_fees=0;

collection_fees=data.collection_fees;

document.getElementById("recharge").value=price;

document.getElementById("collection_fees").value=collection_fees;

}

action部分

public ActionForward getMoney(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) {

response.setContentType("text/html; charset=utf-8");

try {

IElementaryFileService ggsv = new ElementaryFileService();

String pk_card_type = request.getParameter("pk_card_type");

Card_TypeVO ctvo=new Card_TypeVO();

ctvo=ggsv.queryByPK(Card_TypeVO.class, pk_card_type);

PrintWriter out = response.getWriter();

// 这里的数据拼装一般是从数据库查询来的

JSONObject jsonObject = new JSONObject();

if(ctvo!=null){

jsonObject.put("price", ctvo.getCard_money());

jsonObject.put("collection_fees", ctvo.getCash());

}else{

jsonObject.put("price", 0);

jsonObject.put("collection_fees", 0);

}

out.print(jsonObject.toString());

out.flush();

out.close();

return null;

} catch (Exception e) {

e.printStackTrace();

return null;

}

}


当前标题:java代码json,java代码例子
文章源于:http://cdkjz.cn/article/hegjph.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220