How to use JSON to implement the # Communication and communication between Java and C

Source: Internet
Author: User
Tags contains dateformat json static class tojson rabbitmq

We often have to involve in the project communication between the modules, which is inevitable to encounter the communication between the various languages, such as a previous project is a Java message needs to receive C #, (the specific message is how the transmission can use RABBITMQ, etc., The summary of the use of RABBITMQ can be seen in my previous blog, are object-oriented language, and object-oriented message how to resolve to C # is a difficult problem. The following is a summary of the specific ways in which you can use the JSON cipher to communicate between Java and C #.

Absrtact: JSON is a tool for communication between Java and C #, the Java side transforms Java objects into JSON strings, and the C # end receives the JSON strings and converts them to C # objects, and C # emits objects that are transformed into JSON strings, which are parsed into Java objects after Java has been received. The JSON string acts as a bridge between different languages. There is a handy way to generate JSON strings for defined Java or C # objects, and to generate Java or C # objects from JSON strings, which is the use of jackson,c# in Java With Newtonsoft.json, there are some issues to be noted, such as the question of the common type conversion of time, and here is my summary of this.

Key words: Json,java,c#,jackson,newtonsoft

Prerequisite: Java write some kind of program, C # write some kind of program.

Requirements: Java programs and C # programs they need to exchange some information, the information is originally wrapped in the form of objects.

Description: Use Jackson-all-1.9.0.jar and Newtonsoft.Json.dll.

One, Java

The following is a simple example of a Java class that contains 3 properties and provides two ways for objects to go with the JSON string.

Publicclassnotifyrealtimemessage implementsserializable {private static Objectmapper mapper = new Objec
     
    Tmapper ();
        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;
    The public void Setmessage (Object message) {this.message = message;
    Public Calendar GetTime () {return time;
    public void SetTime (Calendar time) {this.time = time;
   /** * Generate JSON String *  */Public String Tojson () throws Jsongenerationexception, Jsonmappingexception, IOException {
    Return mapper.writevalueasstring (this); /** * Build Notifyrealtimemessage object from JSON String */public static notifyrealtimemessage Fromjson (S Tring JSON) throws Jsonparseexception, Jsonmappingexception, IOException {if (json = = n
        ull) {return null;
        else {return mapper. ReadValue (JSON, notifyrealtimemessage.class); }
    }
     
}

The Tojson method converts the Notifyrealtimemessage object into a JSON string, Fromjson the static method converts a JSON string into a Notifyrealtimemessage object. Because the Notifyrealtimemessage object contains a calendar field of a time type, it is necessary to give mapper a predefined time format, mapper. Setdateformat. Use it in this way: notifyrealtimemessage notifymessage = Notifyrealtimemessage.fromjson (JSON); String Json=notifymessage.tojson ();.

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/csharp/

Second, C #

The following is the C # class corresponding to the Java class, which also contains three attributes, but does not provide a way to convert to the JSON string, noting that the names in the Jsonproperty tag are the same as those in the Java class.

public class realtimedatamsg
{
        [Jsonproperty (' MessageType ')] public
        int MessageType {get; set;}
     
        [Jsonproperty ("Geodata")]
        Public geodata Data {get; set;}
     
        [Jsonproperty ("Time")]
        Public DateTime time {get; set;}
     
}

The following is a generic tool class for converting between various C # objects and JSON strings, which is implemented using generics, which provides two ways for objects to go with the JSON string.

 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);  The public static string tojson<t> (T data) {return Jsonconvert.serializeobject (data)
        Myjsonserializersettings); }
}

It is also handy to use in C #, realtimedatamsg realmsg = jsonhelper.fromjson<realtimedatamsg> (JSON); string json = Jsonhelper.tojson (REALMSG); There is also a need to set the myjsonserializersettings time format: Yyyy-mm-dd HH:mm:ss so that the Java-generated JSON string can be parsed correctly.

In this way, the Java end and C # end are done, and got a new headset, has not been cooked, pot headphones go!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.