如何用Java向kafka发送json数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何用Java向kafka发送json数据相关的知识,希望对你有一定的参考价值。

发送json也可以看成字符串处理
We have 2 Options as listed below

1) If we intend to send custom java objects to producer, We need to create a serializer which implements org.apache.kafka.common.serialization.Serializer and pass that Serializer class during creation of your producer

Code Reference below

public class PayloadSerializer implements org.apache.kafka.common.serialization.Serializer

public void configure(Map map, boolean b)



public byte[] serialize(String s, Object o)

try
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
byte[] b = baos.toByteArray();
return b;
catch (IOException e)
return new byte[0];



public void close()



And set the value serializer accordingly

<entry key="value.serializer"
value="com.spring.kafka.PayloadSerializer" />
2) No need to create custom serializer class. Use the existing ByteArraySerializer, but during send follow the process

Java Object -> String (Preferrably JSON represenation instead of toString)->byteArray
参考技术A 文档,序列化成String就行了

如何用java递归生成带children的json串啊?数据集已经有了在下面。

如题对应的字段如下,大侠帮帮忙啊 ! (其中children是那些lft,rgt值中间的一些菜单,depth是该菜单的深度,code不用考虑)
------------------------------ id, menu_Name ,lft,rgt,m_code,depth
Depart dept1= new Depart(1, "ELECTRONICS", 1, 20, "code", 0); Depart dept2= new Depart(2, "TELEVISIONS", 2, 9, "code", 1); Depart dept3= new Depart(3, "TUBE", 3, 4, "code", 2); Depart dept4= new Depart(4, "LCD", 5, 6, "code", 2); Depart dept5= new Depart(5, "PLASMA", 7, 8, "code", 2); Depart dept6= new Depart(6, "PORTABLE ELECTRONICS", 10, 19, "code", 1); Depart dept7= new Depart(7, "MP3 PLAYERS", 11, 14, "code", 2); Depart dept8= new Depart(8, "FLASH", 12, 13, "code", 3); Depart dept9= new Depart(9, "CD PLAYERS", 15, 16, "code", 2); Depart dept10= new Depart(10, "2 WAY RADIOS", 17, 18, "code", 2);

"items": [
"children":[

"children": [

"children": [children。。。。。],//递归即可

"text": "TELEVISIONS"


"children": [

"children": [children。。。。。],//递归即可

"text": "PORTABLE ELECTRONICS"
]
],
text:'ELECTRONICS'
]

。。。。。略

参考技术A 不清楚你的业务需求。
1、数据存放在xml文件中,读取xml文件
2、json格式,如果你的数据有规律可循,可以用代码循环遍历
3、如果数据来自数据库,那么使用sql,一般的数据库都提供查询“树”的sql
参考技术B 使用simplejson这个开源项目包就行

以上是关于如何用Java向kafka发送json数据的主要内容,如果未能解决你的问题,请参考以下文章

java中如何用json格式发送并接受arrayList?

如何用jquery $.ajax向aspx页面传递json格式数据

如何用java程序给微信用户发送消息,麻烦请给出实例,谢谢!急求

如何用java获取百度API返回的json数据的?

如何用java实现list转换成json格式

如何用java语法解析接口返回的json串?