开发者

Using XStream to deserialize an XML response with separate "success" and "failure" forms?

I am planning on using XStream with Java to convert between objects and XML requests and XML responses and objects, where the XML is flowing over HTTP/HTTPS. On the response side, I can get a "successful" response, which seems like it would map to one Java class, or a "failure" response, which seems like it would map to another Java class.

For example, for a "file list" request, I could get an affirmative response e.g.,

<?xml version="1.0" encoding="UTF-8"?>
<response>
  <success>true</success>
  <files>
    <file>[...]</file>
    <file>[...]</file>
    <file>[...]</file>
  </files>
</response>

or I could get a negative response e.g.,

<?xml version="1.0" encoding="UTF-8"?>
<response>
  <success>false</success>
  <error>
    <errorCode>-502</errorCode>
    <systemMessage>[...]AuthenticationException</systemMessage>
    <userMessage>Not authenticated</userMessage>
  </error>
</response>

To handle this, should I include 开发者_如何学Gofields in one class for both cases or should I somehow use XStream to "conditionally" create one of the two potential classes?

The case with fields from both response cases in the same object would look something like this:

Class Response {
  boolean success;
  ArrayList<File> files;
  ResponseError error;
  [...]
}

Class File {
  String name;
  long size;
  [...]
}

Class ResponseError {
  int errorCode;
  String systemMessage;
  String userMessage;
  [...]
}

I don't know what the "use XStream and create different objects in case of success or error" looks like. Is it possible to do that somehow? Is it better or worse way to go?

Anyway, any advice on how to handle using XStream to deal with this success vs. failure response case would be appreciated. Thanks in advance!


I've only used XStream briefly, and quite a few years ago, but if you want two different classes why not have two different root tags (e.g. success and failure) for the two cases?

If you're generating the XML with XStream as well, the classes could have a common base class or interface if that's necessary to make things work on the server side.


In actually working with this I am finding that the first case (include fields in one class for both cases) seems to be working just fine, so maybe that's the way to go.

That being this case where both the successful and unsuccessful forms of Response set the success field and, in the case of an unsuccessful one, the ResponseError is also returned.

Class Response {
  boolean success;
  ArrayList<File> files;
  ResponseError error;
  [...]
}

Class File {
  String name;
  long size;
  [...]
}

Class ResponseError {
  int errorCode;
  String systemMessage;
  String userMessage;
  [...]
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜