我們在項目裡經常要涉及到各模塊間的通信,這其中又不可避免要碰到各類語言間之間的通信,比如之前做的一個項目裡面就是Java發的消息需要C#接收,(具體消息是怎麼傳輸的可以使用RabbitMQ等,關於RabbitMQ的使用總結可以看我之前的博客),都是面向對象的語言,而面向對象的消息怎麼反解析到C#是個難題。下面就是使用Json密器讓Java和C#溝通的具體辦法的總結。
摘要:Json是Java和C#之間通信的利器,Java端將Java對象轉變為Json串後發出,C#端接收到Json串後轉換為C#對象;C#發出轉變為Json串的對象,Java收到後解析成Java對象,Json串在不同語言之間起到一個橋梁的作用。對定義的Java或C#對象生成Json字串,以及從Json字串生成Java或C#對象,有很方便的方法,那就是Java下使用jackson,C#下使用Newtonsoft.Json,其中還有一些問題需要注意,如關於時間這種常見類型轉換的問題,以下便是我對這方面的總結。
關鍵詞:Json,Java,C#,jackson,Newtonsoft
前提:Java寫的某種程序,C#寫的某種程序。
需求:Java程序和C#程序它們之間需要交換某些信息,信息原本是用對象的形式封裝的。
說明:使用jackson-all-1.9.0.jar及Newtonsoft.Json.dll。
一、Java
下面是一個簡單的Java類示例,它包含了3個屬性,並且提供了對象與Json串互轉的兩個方法。
publicclassNotifyRealTimeMessage implementsSerializable {
private static ObjectMapper mapper = new ObjectMapper();
static {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
mapper.setDateFormat(dateFormat);
}
@JsonProperty("messageType")
private int type;
@JsonProperty("geoData")
private Object message;
@JsonProperty("time")
private Calendar time;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Object getMessage() {
return message;
}
public void setMessage(Object message) {
this.message = message;
}
public Calendar getTime() {
return time;
}
public void setTime(Calendar time) {
this.time = time;
}
/**
* 產生Json串
*
*/
public String toJson() throws JsonGenerationException,
JsonMappingException, IOException {
return mapper.writeValueAsString(this);
}
/**
* 從Json字符串構建NotifyRealTimeMessage對象
*
*/
public static NotifyRealTimeMessage fromJson(String json) throws JsonParseException,
JsonMappingException, IOException {
if (json == null) {
return null;
} else {
return mapper
.readValue(json, NotifyRealTimeMessage.class);
}
}
}
toJson方法將NotifyRealTimeMessage對象轉化為一個Json字符串,fromJson靜態方法將一個Json串轉化為一個NotifyRealTimeMessage對象,由於NotifyRealTimeMessage對象中包含一個時間類型的Calendar字段,故事先需要給mapper設定約定好的時間格式,mapper.SetDateFormat。這樣使用它:NotifyRealTimeMessage notifyMessage = NotifyRealTimeMessage.fromJson(json);String json=notifyMessage.toJson();。
查看本欄目