Given a MIME string, how can I parse it to extract the cha开发者_C百科rset? And is there a utility to map the different MIME types to object types (e.g., return 'xml' for both text/xml and application/xml)
Well, given a byte array of a known character set, the conversion to String is trivial:
String result = new String(byteArray, charset);
So your first question is reduced to "what's the easiest way to extract a charset from the mime type?". This depends on the range of inputs you expect to be able to handle and what libraries you're already using. One way of doing this, for example, is using javax.mail.internet.ContentType
to do the parsing; I'm sure other libraries provide similar functionality.
As for the second part, I'm not sure what you mean by "convert to an object". Everything in Java (excluding primitives) is an Object
already; if you're talking about something more specific, then you'd need to be more specific. There's no generic framework available that will magically convert from anything to anything, so you'll need to narrow down your requirements there a bit.
Jersy's MediaType has a valueOf static method to parse MIME.
It also has support for creating object given a value stream. Unfortunately, it looks like it cannot be used separately.
With the approach of Andrzej, if you mean that String object which you just got is an XML then there are ways to convert it to Java object. A simple technique is;
- Create an XML Document Object from the String.
- Convert the XML Document object to Java object.
There are various libraries/APIs available to do the 2nd part. Few to refer;
- Castor (http://www.castor.org/xml-framework.html)
- XStream (http://x-stream.github.io/)
The libraries are fairly easy to use.
JSON.parse(JSON.stringify(mime)) This worked for me
精彩评论