json库在golang中的使用

json库在golang中的使用,第1张

golang对json序列化和反序列化的 *** 作实在是难受,所以说用习惯了高级语言特性,再转到这些偏原生的写法上就会很难受。

不多BB,开始记录。

当写个小demo或者做个小工具,没有大规模使用场景,那使用哪个库都是一样的,因为性能的体现并不会很明显。但是如果是在实际项目中使用,且伴随着高并发,大容量等场景,我还是推荐使用 json-iterator 。

号称最快的go json解析器。跟官方的写法兼容,我目前基本都使用这个。

https://github.com/json-iterator/go

效率对比

ns 纳秒 op *** 作

俩种方式,一种直接反序列化成 结构体数组,另一种反序列化为 slice,内容为map[string]interface{}

结构体数组

slice

http://www.zhouhuibo.club

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/htmlcharset=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

}

}

moshi 是square开源的JSON解析库,square出品必属精品,moshi确实解决了不少问题,使用起来也比较简单,方便。

moshi支持java基本类型和对应的包装类型,String,list,map还有Enum

对于有些不支持的数据类型,可以自定义adapter进行类型转换。ex:

例如android中经常用的color:

json字符串:

java中的实体类

因为json中的color字段对应的是字符串,而java中的color是int,直接反序列化,程序会抛出异常。moshi 可以使用下面的方法解决这个问题。

给字段加上标识:

class Rectangle {

int width

int height

@HexColor int color

}

对于一些不需要序列化和反序列化的字段可以使用 transient 关键字标注,这样moshi在序列化和反序列化时就会跳过这个字段。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/sjk/6851725.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-29
下一篇 2023-03-29

发表评论

登录后才能评论

评论列表(0条)

保存