IttayD
IttayD

Reputation: 29123

convert from byte array and mime type to string / object

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)

Upvotes: 1

Views: 3100

Answers (4)

Scott Lexium
Scott Lexium

Reputation: 61

JSON.parse(JSON.stringify(mime)) This worked for me

Upvotes: 0

Tushar Tarkas
Tushar Tarkas

Reputation: 1612

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://x-stream.github.io/)

The libraries are fairly easy to use.

Upvotes: 0

IttayD
IttayD

Reputation: 29123

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.

Upvotes: 0

Andrzej Doyle
Andrzej Doyle

Reputation: 103797

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.

Upvotes: 1

Related Questions