tags:

views:

153

answers:

3

Given a MIME string, how can I parse it to extract the charset? 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)

+1  A: 

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.

Andrzej Doyle
A: 

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;

  1. Create an XML Document Object from the String.
  2. Convert the XML Document object to Java object.

There are various libraries/APIs available to do the 2nd part. Few to refer;

  1. Castor (http://www.castor.org/xml-framework.html)
  2. XStream (http://xstream.codehaus.org/)

The libraries are fairly easy to use.

Tushar Tarkas
A: 

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.

IttayD