jsonchange(jsonchange并执行)

http://www.itjxue.com  2023-02-24 21:50  来源:未知  点击次数: 

如何实现实体与json的转化

在开发的过程中,会遇到实体与json格式转化以便符合微信接口需要的json格式以及请求接口获取的json转化为实体。我把一些公用的方法总结如下(特别说明:解析是用的flexJson):

import java.util.ArrayList;

import java.util.List;

import flexjson.JSONDeserializer;

import flexjson.JSONSerializer;

public class JsonUtil {

/**

* 对象转化为字符串

* @param obj 要转化为json字符串的实体

*/

public static String getJsonStrFromObj(Object obj) {

JSONSerializer serializer = new JSONSerializer();

return serializer.serialize(obj);

}

/**

* 对象转化为json字符串

* @param obj 实体

* @param inParams 包含的字段数组

* @param exparams 不需要包含的字段

*/

public static String getJsonStrFromObj(Object obj, String[] inParams,String[] exParams) {

JSONSerializer serializer = new JSONSerializer();

serializer = serializer.include(inParams).exclude(exParams);

return serializer.serialize(obj);

}

/**

* 将对象转化为json字符串

* @param obj 实体

* @param exParams 不要包括的字段

*/

public static String getJsonStrFromObj(Object obj,String[] exParams) {

JSONSerializer serializer = new JSONSerializer();

serializer = serializer.exclude(exParams);

return serializer.serialize(obj);

}

/**

* 将List转化为json字符串

* @param objs list对象

* @return

*/

public static String getJsonStrFromList(ListObject objs){

return new JSONSerializer().exclude("class").serialize(objs);

}

/**

* 将List转化为json字符串

* @param objs list对象

* @param rootName 根名

* @param params 包括的字段

* @return

*/

public static String getJsonStrFromList(ListObject objs, String rootName,

String[] params) {

JSONSerializer serializer = new JSONSerializer();

serializer = serializer.include(params).exclude("class");

serializer.rootName(rootName);

return serializer.serialize(objs);

}

/**

* 将List转化为json字符串

* @param objs list对象

* @param rootName 根名

* @param params 包括的字段

* @return

*/

public static String getJsonStrFromList(ListObject objs, String rootName) {

JSONSerializer serializer = new JSONSerializer();

// serializer = serializer.exclude("class");

serializer.rootName(rootName);

return serializer.serialize(objs);

}

/**

* 将List转化为json字符串

* @param objs list对象

* @param rootName 根名

* @param params 包括的字段

* @return

*/

public static String getJsonStrFromList(ListObject objs, String[] params) {

JSONSerializer serializer = new JSONSerializer();

serializer = serializer.include(params).exclude("class");

return serializer.serialize(objs);

}

/**

* 将List转化为json字符串

* @param objs list对象

* @param rootName 根名

* @param params 包括的字段

* @return

*/

public static String getJsonStrFromList(ListObject objs, String[] inParams,String[] exParams) {

JSONSerializer serializer = new JSONSerializer();

serializer = serializer.include(inParams).exclude("class").exclude(exParams);

return serializer.serialize(objs);

}

/**

* 将字符串转化为实体

* @param T 实体

* @param source 要解析的字符串

* @param bean 要转化为的对象

* @return

*/

public static T T getObjFromJsonStr(String source, ClassT bean) {

return new JSONDeserializerT().deserialize(source, bean);

}

/**

* 将json中包含的class属性去除

* @param json 要转化的json

* @return

*/

public static String changeJson(String json){

int i = json.indexOf("\"class\":");

if(i!=-1){

int j = json.indexOf(",", i+1);

char c = json.charAt(j);

String subString="";

if((c+"").equals(",")){//第一个属性或者中间的属性出现

subString = json.substring(i, j+1);

}else if((c+"").equals("}")) {//在结尾的属性出现

subString = json.substring(i-1, j);

}

return json.replaceAll(subString, "");

}

return json;

}

}

请教json数据怎么在Controller接收

通过ajax方式在后台控制器接受

$("#xianluly").change(function () {

if ($("#xianluly").val() == "旅行社") {

$.ajax({

type: "POST", async: false, //用POST方式传输

url: '/HYFX/GetMem_TH', //目标地址

error: function (XMLHttpRequest, textStatus, errorThrown) {

alert("失败");

},

success: function (data) {

if (data != "") {

//成功

}

else {

alert("失败");

}

}

});

}

else

{ $("#spanly").hide(); }

});

后台和以前获取一样,通过request来获取就可以

C#怎么实现 实现 类的自动映射

有时候会遇到这样的问题,两个对象具有很多相同的属性,已知一个对象,要给另外一个对象赋值,这时候需要每个属性逐一赋值,会比较麻烦。

如果不考虑性能问题的话,可以使用对象映射的方式来赋值,实际上是利用了反射的机制,达到动态生成对象和动态类型转换的目的。

实现代码如下

using System;

using Newtonsoft.Json;

namespace ConsoleApplicationTest

{

class Program

{

static void Main(string[] args)

{

string s = string.Empty;

var person = new Person { Name = "张三", Age = "12", Birthday = "2015/10/31 19:56:30" };

var student = EntityMapperStudent, Person(person);

s = JsonConvert.SerializeObject(student);

Console.WriteLine(s);

Console.ReadKey();

}

static TTo EntityMapperTTo, TFrom(TFrom from)

{

var to = Activator.CreateInstanceTTo();

var tTo = typeof(TTo);

var psFrom = typeof(TFrom).GetProperties();

foreach (var pFrom in psFrom)

{

var vFrom = pFrom.GetValue(from);

if (vFrom != null)

{

var pTo = tTo.GetProperty(pFrom.Name);

if (pTo != null)

{

var pToType = pTo.PropertyType;

if (pToType.IsGenericType pToType.GetGenericTypeDefinition() == typeof(Nullable))

{

var vTo = Convert.ChangeType(vFrom, pToType.GetGenericArguments()[0]);

pTo.SetValue(to, vTo);

}

else

{

var vTo = Convert.ChangeType(vFrom, pTo.PropertyType);

pTo.SetValue(to, vTo);

}

}

}

}

return to;

}

public class Person

{

public string Name { get; set; }

public string Age { get; set; }

public string Birthday { get; set; }

}

public class Student

{

public string Name { get; set; }

public int Age { get; set; }

public DateTime Birthday { get; set; }

}

}

}

有谁能把下面的json的代码用通过程序后台把它给解析出来吗,无论用什么办法都行,算是小弟求求高手了..

用Jquery获取,稍等,我写个function给你 ,你这个是在什么页面得到的JSON数据,,我要是一个个TITILE对的话很慢的 最好把页面发给我 ,,taobao的json??

实例如下,其他的你自己按照这个步骤写就OK了

script src="js/jquery-1.5.2.min.js" type="text/javascript"/script

script type="text/javascript"

//淘宝Json数据解析

$(document).ready(function(){

$('#btnChange').click(function(){

var data = eval("("+ $("#lblData").html() + ")");

//交易信息

var tradeinfo = data.trades_sold_get_response.trades.trade

var strResultHtml = $('#lblResult')

strResultHtml.append("买家昵称:" + tradeinfo[0].buyer_nick)

strResultHtml.append("br/买家获取点数:" + tradeinfo[0].buyer_obtain_point_fee)

strResultHtml.append("br/买家好评率:" + tradeinfo[0].buyer_rate)

strResultHtml.append("br/订单创建时间:" + tradeinfo[0].created)

});

});

/script

label id="lblData"

{"trades_sold_get_response":

{"trades":

{"trade":[{

"buyer_nick":"夏夏海洋星",

"buyer_obtain_point_fee":0,

"buyer_rate":false,

"created":"2011-08-22 13:37:40",

"orders":{

"order":[

{"num":1,"pic_path":"http:\/\/img02.taobaocdn.com\/bao\/uploaded\/i2\/T1TVd1Xh0mXXamuZk._111505.jpg",

"price":"59.00","refund_status":"WAIT_SELLER_AGREE","sku_id":"9262433250","title":"麦考林 童装 小小航海家英雄勋章拉链衫"},

{"num":1,"pic_path":"http:\/\/img03.taobaocdn.com\/bao\/uploaded\/i3\/T1FEl0XgBDXXcfOKcW_023218.jpg",

"price":"35.00","refund_status":"WAIT_SELLER_AGREE","sku_id":"9090237554","title":"麦考林 童装 小小航海家Q版海盗T恤"},

{"num":1,"pic_path":"http:\/\/img01.taobaocdn.com\/bao\/uploaded\/i1\/T1jEx0XghzXXauDwsT_011702.jpg",

"price":"99.00","refund_status":"WAIT_SELLER_AGREE","sku_id":"9085695112","title":"麦考林 童装 男童潮童运动套装"}

]

},

"pay_time":"2011-08-22 13:39:32",

"payment":"213.00",

"point_fee":0,

"real_point_fee":0,

"receiver_address":"阳光100 F15-5-302",

"receiver_zip":"250022",

"seller_nick":"eurokids麦考林专卖",

"seller_rate":false,

"sid":"90106462245083",

"status":"WAIT_SELLER_SEND_GOODS",

"tid":90106462245083,

"title":"eurokids麦考林专卖",

"total_fee":"193.00",

"type":"fixed"

}]

},

"total_results":6}

}

/labelbr /

input type="button" id="btnChange" value="ChangeJsonToData" /br /

label id="lblResult"/label

java读取json文件的问题

Java 读写json格式的文件方法:

一、要解决这个问题首先要知道json格式是什么?

JSON格式:

比如学生有学号,姓名,性别等。

用json表示则为:

{"studno":"11111","studname":"wwww","studsex":"男"}(各个字段都是字符型)

这代表一个学生的信息。

如果多个,如下:

[{"studno":"122222","studname":"wwww","studsex":"男"},

{"studno":"11111","studname":"xxxx","studsex":"男"},

{"studno":"33333","studname":"ssss","studsex":"男"}]

这就是json格式。

二、那如何操作json格式的文件呢?

解答:就是直接读写文件,再把读出来的文件内容格式化成json就可以了。

三、具体操作:

1、有一个实体类,如下:

public?class?ElectSet?{

public?String?xueqi;

public?String?xuenian;

public?String?startTime;

public?String?endTime;

public?int?menshu;

public?String?isReadDB;

//{"xueqi":,"xuenian":,"startTime":,"endTime":,"renshu":,"isReadDB":}

public?String?getXueqi()?{

???return?xueqi;

}

public?void?setXueqi(String?xueqi)?{

???this.xueqi?=?xueqi;

}

public?String?getXuenian()?{

???return?xuenian;

}

public?void?setXuenian(String?xuenian)?{

???this.xuenian?=?xuenian;

}

public?String?getStartTime()?{

???return?startTime;

}

public?void?setStartTime(String?startTime)?{

???this.startTime?=?startTime;

}

public?String?getEndTime()?{

???return?endTime;

}

public?void?setEndTime(String?endTime)?{

???this.endTime?=?endTime;

}

public?int?getMenshu()?{

???return?menshu;

}

public?void?setMenshu(int?menshu)?{

???this.menshu?=?menshu;

}

public?String?getIsReadDB()?{

???return?isReadDB;

}

public?void?setIsReadDB(String?isReadDB)?{

???this.isReadDB?=?isReadDB;

}

}

2.有一个json格式的文件,存的就是他的信息,如下:

Sets.json:

{"xuenian":"2007-2008","xueqi":"1","startTime":"2009-07-19?08:30","endTime":"2009-07-22?18:00","menshu":"10","isReadDB":"Y"}

3.具体操作:

/*

*?取出文件内容,填充对象

*/

public?ElectSet?findElectSet(String?path){

???ElectSet?electset=new?ElectSet();

???String?sets=ReadFile(path);//获得json文件的内容

???JSONObject?jo=JSONObject.fromObject(sets);//格式化成json对象

???//System.out.println("------------"?jo);

???//String?name?=?jo.getString("xuenian");

???//System.out.println(name);

???electset.setXueqi(jo.getString("xueqi"));

???electset.setXuenian(jo.getString("xuenian"));

???electset.setStartTime(jo.getString("startTime"));

???electset.setEndTime(jo.getString("endTime"));

???electset.setMenshu(jo.getInt("menshu"));

???electset.setIsReadDB(jo.getString("isReadDB"));

???return?electset;

}

//设置属性,并保存

public?boolean?setElect(String?path,String?sets){

???try?{

????writeFile(path,sets);

????return?true;

???}?catch?(IOException?e)?{

????//?TODO?Auto-generated?catch?block

????e.printStackTrace();

????return?false;

???}

}

//读文件,返回字符串

public?String?ReadFile(String?path){

????File?file?=?new?File(path);

????BufferedReader?reader?=?null;

????String?laststr?=?"";

????try?{

?????//System.out.println("以行为单位读取文件内容,一次读一整行:");

?????reader?=?new?BufferedReader(new?FileReader(file));

?????String?tempString?=?null;

?????int?line?=?1;

?????//一次读入一行,直到读入null为文件结束

?????while?((tempString?=?reader.readLine())?!=?null)?{

??????//显示行号

??????System.out.println("line?"?line?":?"?tempString);

??????laststr?=?laststr?tempString;

??????line?;

?????}

?????reader.close();

????}?catch?(IOException?e)?{

?????e.printStackTrace();

????}?finally?{

?????if?(reader?!=?null)?{

??????try?{

???????reader.close();

??????}?catch?(IOException?e1)?{

??????}

?????}

????}

????return?laststr;

}

?????????//把json格式的字符串写到文件

public?void?writeFile(String?filePath,?String?sets)?throws?IOException?{

????FileWriter?fw?=?new?FileWriter(filePath);

????PrintWriter?out?=?new?PrintWriter(fw);

????out.write(sets);

????out.println();

????fw.close();

????out.close();

???}

4.调用,使用(在网站的controller里调用的):

//取出json对象

public?void?GetElectSettings(HttpServletRequest?request,

????HttpServletResponse?response)?throws?Exception?{

???ElectSet?electset=new?ElectSet();

???String?absPath?=?request.getRealPath("\");

???String?filePath?=?absPath?"public\sets\electSets.json";

???electset=businessService.findElectSets(filePath);//这里是调用,大家自己改改,我调用的业务层?的。

???JSONArray?jsonItems?=?new?JSONArray();

???jsonItems.add(electset);

???JSONObject?jo=new?JSONObject();

???jo.put("data",?jsonItems);

???System.out.println(jo);

???request.setCharacterEncoding("utf-8");

???response.setContentType("application/json;charset=utf-8");

???PrintWriter?out?=?response.getWriter();

???out.print(jo);

}

//修改json文件

public?void?ChangeElectSet(HttpServletRequest?request,

????HttpServletResponse?response)?throws?Exception?{

???request.setCharacterEncoding("UTF-8");

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

???log.info("reach?ChangeElectSet");

???String?json?=?(String)?request.getParameter("json").trim();

???log.info("Change?ElectSet");

???log.info(json);

???ElectSet?sets?=?new?ElectSet();

???JSONObject?jsonObject?=?JSONObject.fromObject(json);

???sets?=?(ElectSet)?JSONObject.toBean(jsonObject,?ElectSet.class);

???if(sets.getIsReadDB()=="false"){

????sets.setIsReadDB("否");

???}

???else{

????sets.setIsReadDB("是");

???}

???String?changes="{"xuenian":"";//因为json的属性要用引号,所以要用"转义一下

???changes?=sets.getXuenian()?"","xueqi":""?sets.getXueqi()?"","startTime":""?sets.getStartTime()?"","endTime":""?sets.getEndTime()?"","menshu":""?sets.getMenshu()?"","isReadDB":""?sets.getIsReadDB()?""}";

???System.out.println(changes);

???String?absPath?=?request.getRealPath("\");

???String?filePath?=?absPath?"public\sets\electSets.json";

json里面changeobjecttostring的方法如果对象为空值是转换成什么

JSON.stringify(要转换的object对象)。此方法返回的就是一个类似于{“name”:"张三","age":18}这样的字符串

(责任编辑:IT教学网)

更多

推荐免费资源文章