使用Json讓Java和C#溝通的方法


最近很忙啊,新項目下來了,都沒時間寫博客了。頻率降低點,但不能不總結跟大家分享啊。

我們在項目里經常要涉及到各模塊間的通信,這其中又不可避免要碰到各類語言間之間的通信,比如之前做的一個項目里面就是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串互轉的兩個方法。
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class NotifyRealTimeMessage implements Serializable {   
     
     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();。

 

二、C#

以下是與Java類對應的C#類,它也包含了三個屬性,但沒提供與Json串轉換的方法,注意JsonProperty標簽里的名字跟Java類里的一樣。
 

 

1
2
3
4
5
6
7
8
9
10
11
12
public class RealTimeDataMsg
{
         [JsonProperty( "messageType" )]
         public int MessageType { get ; set ; }
 
         [JsonProperty( "geoData" )]
         public GeoData Data { get ; set ; }
 
         [JsonProperty( "time" )]
         public DateTime Time { get ; set ; }
 
}
下面的是一個通用的做各類C#對象與Json字串之間轉化的工具類,它使用泛型來實現,它提供了 對象與Json串互轉的兩個方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public static class JsonHelper
{
         private static readonly  JsonSerializerSettings MyJsonSerializerSettings;
 
         static JsonHelper()
         {
            MyJsonSerializerSettings = new JsonSerializerSettings();
            IsoDateTimeConverter dateTimeConverter = new IsoDateTimeConverter();
            dateTimeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss" ;
            MyJsonSerializerSettings.Converters.Add(dateTimeConverter);
         }
 
         public static T FromJson<T>( string json)
         {
             if ( string .IsNullOrEmpty(json))
             {
                 return default (T);
             }
             return JsonConvert.DeserializeObject<T>(json, MyJsonSerializerSettings);
         }
 
         public static string ToJson<T>(T data)
         {
            return JsonConvert.SerializeObject(data, MyJsonSerializerSettings);
         }
}

在C#中,使用起來也很方便,RealTimeDataMsg realMsg = JsonHelper.FromJson<RealTimeDataMsg>(json);string json = JsonHelper.ToJson(realMsg);這里同樣需要給MyJsonSerializerSettings設置好事先約定的時間格式:yyyy-MM-dd HH:mm:ss,這樣才能正確的解析Java生成的Json串。

這樣,Java端和C#端都做好了,搞了一個新耳機,還沒煲好,煲耳機去嘍!

 

 

 






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM