利用method.invoke(..)解析json

//调用

iniJSONObject(Person.class.getName(), createJSONObject());

iniJSONObject2(World.class.getName(), createJSONObject2());

/**

* 只是一个普通的对象

*

* @param name

*            (包名+类名)

* @return

*/

private Object iniJSONObject(String name, JSONObject jsonObject) {

try {

//只放类名是错的...........

// Class<?> forName = Class.forName("Person");

// 包名+类名,正确的

//String name2 = Person.class.getName();

Class<?> forName = Class.forName(name);

Object newInstance = forName.newInstance();

Method[] methods = forName.getMethods();

HashMap<String, Method> hashMap = new HashMap<String, Method>();

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

String methodName = methods[i].getName();

System.out.println(forName + "方法列表:" + methodName);

hashMap.put(methodName, methods[i]);

}

// 获取JSONObject的key字段列表.........

// 获取JSONObject的key字段列表.........

// 获取JSONObject的key字段列表.........

Iterator iterator = jsonObject.keys();

while (iterator.hasNext()) {

String key = iterator.next().toString();

Object value = jsonObject.get(key);

// userName

// userAge

// userHobby

System.out.println("jsonObject的key=" + key);

// 看方法列表有没有该set方法

if (hashMap.containsKey("set" + wordFirstToUpper(key))) {

Method method = hashMap.get("set" + wordFirstToUpper(key));

String methodName = method.getName();

String type = method.getParameterTypes()[0].getName();

// 调用方法...........

method.invoke(newInstance, value);

System.out.println("调用方法:" + methodName + "方法的参数类型是:" + type+"值得类型:"+value.getClass().getName());

}

}

System.out.println("解析结果:" + newInstance.toString());

return newInstance;

} catch (JSONException e) {

e.printStackTrace();

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

}

return null;

}

/**

* 对象里有对象

*

* @param name

*            (包名+类名)

* @param jsonObject

*/

private void iniJSONObject2(String name, JSONObject jsonObject) {

try {

Class<?> forName = Class.forName(name);

Object newInstance = forName.newInstance();

// 获取该类的方法列表

Method[] methods = forName.getMethods();

HashMap<String, Method> hashMap2 = new HashMap<String, Method>();

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

hashMap2.put(methods[i].getName(), methods[i]);

}

Iterator keys = jsonObject.keys();

while (keys.hasNext()) {

// key字段.............

String key = keys.next().toString();

// value

Object object = jsonObject.get(key);

if (hashMap2.containsKey("set" + wordFirstToUpper(key))) {

// 得到该set方法的参数类型

Method method = hashMap2.get("set" + wordFirstToUpper(key));

// 参数的类型(包名+类名)

String type = method.getParameterTypes()[0].getName();

if (object instanceof JSONObject) {

// 是个JSONObject

method.invoke(newInstance,

iniJSONObject(type, (JSONObject) object));

} else if (object instanceof JSONArray) {

} else {

method.invoke(newInstance, object);

}

System.out.println("方法的参数类型:"+type+"/值得类型:/"+object.getClass().getName());

}

}

System.out.println("解析后的结果:" + newInstance.toString());

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (JSONException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

}

}

/**

* @param word

* @return  首字母大写

*/

public static String wordFirstToUpper(String word) {

// int c = word.charAt(0);

// if (c >= 97 && c <= 122) {

// c -= 32;

// }

// return String.format("%c%s", c, word.substring(1));

return word.replaceFirst(word.substring(0, 1), word.substring(0, 1)

.toUpperCase());

}

public JSONObject createJSONObject() {

JSONObject jsonObject = new JSONObject();

try {

jsonObject.put("userName", "wuxifu");

jsonObject.put("userAge", 110);

jsonObject.put("userHobby", 1);

} catch (JSONException e) {

e.printStackTrace();

}

return jsonObject;

}

public JSONObject createJSONObject2() {

JSONObject jsonObject = new JSONObject();

JSONObject jsonObject2 = new JSONObject();

try {

jsonObject.put("person", jsonObject2);

jsonObject.put("nums", 110);

jsonObject.put("ages", 2015);

jsonObject2.put("userName", "wuxifu");

jsonObject2.put("userAge", 110);

jsonObject2.put("userHobby", 1);

} catch (JSONException e) {

e.printStackTrace();

}

return jsonObject;

}

package com.example.testviewpager;

public class Person {

private String userName;

private int   userAge;

private int userHobby;

public Person() {

super();

// TODO Auto-generated constructor stub

}

public Person(String userName, int userAge, int userHobby) {

super();

this.userName = userName;

this.userAge = userAge;

this.userHobby = userHobby;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public int getUserAge() {

return userAge;

}

public void setUserAge(int userAge) {

this.userAge = userAge;

}

public int getUserHobby() {

return userHobby;

}

public void setUserHobby(int userHobby) {

this.userHobby = userHobby;

}

@Override

public String toString() {

return "Person [userName=" + userName + ", userAge=" + userAge

+ ", userHobby=" + userHobby + "]";

}

}

package com.example.testviewpager;

public class World {

private Person person;

private int  nums;

private int  ages;

public World() {

super();

}

public Person getPerson() {

return person;

}

public void setPerson(Person person) {

this.person = person;

}

public int getNums() {

return nums;

}

public void setNums(int nums) {

this.nums = nums;

}

public int getAges() {

return ages;

}

public void setAges(int ages) {

this.ages = ages;

}

@Override

public String toString() {

return "World [person=" + person + ", nums=" + nums + ", ages=" + ages

+ "]";

}

}

时间: 2024-08-28 23:37:02

利用method.invoke(..)解析json的相关文章

js之第三方工具解析JSON

1.JSON 仅仅是一种文本字符串.它被存储在 responseText 属性中 为了读取存储在 responseText 属性中的 JSON 数据,须要依据 JavaScript 的 eval 函数.函数 eval 会把一个字符串当作它的參数. 然后这个字符串会被当作 JavaScript 代码来运行.由于 JSON 的字符串就是由 JavaScript 代码构成的,所以它本身是可运行的 比如例如以下方式: String json = "{username:'一叶扁舟',age:22}&quo

利用Java反射机制和泛型,全自动解析json

有啦这个简直,太爽啦, 利用Java 反射机制,利用Class 就可以得到 类的 变量  Field[] fields=cls.getDeclaredFields(); 还可以通过类中 的方法名字 去执行这个方法 m1 = cls.getDeclaredMethod(getMothodName(fields[j].getName()), String.class); m1.invoke(result,json.getString(fields[j].getName()) ); 利用泛型 去获取这

Android中利用Gson解析Json

在Android开发中,Json是一种客户端与服务器端交互的一种语言,它语法简单,最好的是目前市面上有很便捷的轮子可以对他进行解析.例如,Gson就是google提供的一款用于解析或者生成Json的库,可以直接将Json字符串映射成对应的实体类,十分方便.下面我总结一下利用Gson解析Json的用法以及我遇到的问题. 最简单对象的解析: 例如下边这段Json字符串: { text: "Love", img:"http://img2.imgtn.bdimg.com/it/u=2

利用PBFunc在Powerbuilder中解析Json对象

利用PBFunc工具在Powerbuilder解析json,只需要调用getattribute方法来获取 解析unicode格式的json: n_pbfunc_json lnv_json lnv_json.of_parse('{"test3":"\u6735\u6735\u8d1d\u8d1d\u5a74\u513f\u978b"}') string ls_val lnv_json.getattribute("test3",ls_val) ls_

Android 利用Gson生成或解析json

目前手机端和服务端数据交流格式一般是json,而谷歌提供了Gson来解析json.下载Gson:https://code.google.com/p/google-gson/ 下载的放在lib并导入,若出现错误:java.lang.NoClassDefFoundError: com.google.gson.Gson 是因为没有导入android-support-v4.jar,导入即可. 一.单个对象生成json 生成以下类,该怎么生成呢? { "createDate": "20

利用fastjson解析json并通过js&amp;ajax实现页面的无跳转刷新

1.json是一种优秀的数据格式,在移动开发和web开发中经常用到,本例中通过一个小案例讲解如何通过alibaba的开源框架fastjson来解析jason数据格式并通过js实现无跳转刷新 2,新建一个web项目,这是我的项目:我这里直接用servlet写的 注意导包,我这里到了很多无用的包,其实主要的包是下面几个: 这个三个包是必须的,其他都是开发基本web的常用包 3.创建一个domain: package com.keson.domain; import com.thoughtworks.

kettle 利用 HTTP Client 获取猫眼电影API近期上映相关信息,并解析json输出为Excel文件

前言 Kettle 除了常规的数据处理之外,还可以模拟发送HTTP client/post ,REST client. 实验背景 这周二老师布置了一项实验: 建立一个转换,实现一个猫眼API热映电影的json,生成为xls文件. 猫眼的热门电影接口为:?http://m.maoyan.com/#movie,从里面找到API接口:http://m.maoyan.com/ajax/movieOnInfoList.需要获取里面的:电影名.评分.主演.信息. 处理流程 我使用的是kettle的HTTP

Android异步加载访问网络图片-解析json

来自:http://www.imooc.com/video/7871 推荐大家去学习这个视频,讲解的很不错. 慕课网提供了一个json网址可以用来学习:http://www.imooc.com/api/teacher?type=4&num=30.我们的任务就是建立一个listview,将json提供的一些参数,主要是name,picSmall,description显示出来,效果图如下:  主要思路如下:listview中图片的加载,程序中使用了两种方式,一种是使用Thread类,一种是使用As

Java构造和解析Json数据的两种方法详解二(转)

在www.json.org上公布了很多JAVA下的json构造和解析工具,其中org.json和json-lib比较简单,两者使用上差不多但还是有些区别.下面接着介绍用org.json构造和解析Json数据的方法示例. 一.介绍 org.json包是另一个用来beans,collections,maps,java arrays 和XML和JSON互相转换的包,主要就是用来解析Json数据,在其官网http://www.json.org/上有详细讲解,有兴趣的可以去研究. 二.下载jar依赖包