What libraries are available that can do something like
public class Person {
private Long id;
private Name;
private List<Long> associations;
// accessors
}
public class Name {
private String first;
private String last;
// accessors
}
into something like
id=1
associations=1,2,3,4,5
name.first=Franz
name.last=See
And If there's no library to do that, what's a good way to do it? :-)
I doubt there's a library for that since common way to serialize beans is into XML. You may write simple library yourself using Java Reflection API to get list of properties and extract their values. It would be more common solution than making custom toString() for any class you may need to serialize.
Well I think instead of using any external library you can do it yourself just add getters and setters in your javabeans and override to string method of it and then you can form the string as you want.Then only task remaining is to write that string into one file, thats it!!!!!
Well, you can go check how XMLEncoder extract field names and values from object, and try to rewrite it to output properties files. I think that, by replacing xml output by properties output, you can get a fairly good properties creator. Notice, as an added benefit, that the same goes for properties reading using an equivalent opf XMLDecoder.
Please check if JSON would solve this problem.
import net.sf.json.JSONObject;
public class YourJSONJavaExample
{
public static void main(String args[]){
JSONObject object=new JSONObject();
object.put("firstname","John");
object.put("age",new Integer(21));
object.put("lastname","smith");
System.out.println(object);
}
}
Related
I'm using ProGuard to obfuscate my source code, but I'm running into a problem where my obfuscated code re-uses the same field name for fields with different types. For example:
public class Pojo {
int id;
String name;
}
Becomes:
public class Pojo {
int a;
String a;
}
This is causing problems when trying to use JSON serialization/deserialization, so I'd like to have unique field names instead.
I tried adding -useuniqueclassmembernames though it didn't work. Couldn't see any other options, besides maybe using the -obfuscationdictionary option, but that seems like overkill.
I have a class like this
public class Test {
private String m_username;
public Test() {}
public Test(String username) {
m_username = username;
}
}
And with Moxy. I can post this POJO to other API using Jersey client without any converting operation. But I need to set the m_username as a final field and that will need the empty constructor to initiate m_username. And also the Moxy doesn't work. How can I fix that?
The question isn't very well asked.
AS far as I understand:
You have to make your field final
You have to keep the empty constructor because your object is automatically serialized/deserialized in a format like JSON, using a library such as those you can find in Spring
Unfortunately, these two constraints can't be held at the same time. You will need to abandon final if you want to keep the empty constructor, and conversely.
I have an Java bean class Person containing 3 variables:
name (String)
age (String)
address (Object).
Address contains 3 variables:
street
door_no
city
I would like to have a utility which should print all variables in Person.
By this I mean it should print Person & also the Address object contained in it.
I could create a hashmap and put the variable names & values using reflection and print key/value UI in JSP but the issue is I have to apply reflection for Address to add variable/value in the hashmap.
Is there a utility available to do this?
You could use ToStringBuilder from Apache Commons.
From documentation:
A typical invocation for this method would look like:
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
More details:
This class enables a good and consistent toString() to be built for
any class or object. This class aims to simplify the process by:
allowing field names handling all types consistently handling nulls
consistently outputting arrays and multi-dimensional arrays enabling
the detail level to be controlled for Objects and Collections handling
class hierarchies To use this class write code as follows:
public class Person {
String name;
int age;
boolean smoker;
...
public String toString() {
return new ToStringBuilder(this).
append("name", name).
append("age", age).
append("smoker", smoker).
toString();
}
}
Alternatively, there is a method that uses reflection to determine the
fields to test. Because these fields are usually private, the method,
reflectionToString, uses AccessibleObject.setAccessible to change the
visibility of the fields. This will fail under a security manager,
unless the appropriate permissions are set up correctly. It is also
slower than testing explicitly.
A typical invocation for this method would look like:
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
You're probably looking for Apache Commons ToStringBuilder#reflectionToString(Object).
You may find the Jackson JSON serializer useful for this purpose. The Jackson library may already be part of your stack. If not, find the required dependencies below.
private static final ObjectMapper OBJECT_MAPPER_SINGLETON = new ObjectMapper();
public static String toStringUsingJackson(final Object object) {
try {
return OBJECT_MAPPER_SINGLETON.writeValueAsString(object);
} catch (final JsonProcessingException e) {
return String.valueOf(object);
}
}
Sample output:
{"name":"John Doe","age":42}
Required maven/gradle dependencies:
jackson-core, groupId=com.fasterxml.jackson.core
jackson-databind, groupId=com.fasterxml.jackson.core
You can implement the toString method to print out whatever you want, or you can use Apache Commons ToStringBuilder http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/builder/ToStringBuilder.html and its reflectionToString method. I don't believe this will recurse through the properties (like address for example), but if you want to see Address printed out with Street, Door No and City, use implement its toString method to print that information out.
I have one field which is a composition of two values. This is the field that gets serialized to/from JSON and works great.
public String getRevisions() { return revisions; }
public void setRevisions(String revisions) { this.revisions = revisions; }
I added two helper methods to retrieve the separate values, but I don't want them serialized to JSON.
public String getCurrentRevision() { ... return first revision ... }
public String getPreviousRevision() { ... return second revision ... }
Is there a way I can tell java.beans.Introspector to ignore these additional getters when building the BeanInfo via getBeanInfo()? An annotation would be lovely, and I'm really hoping to avoid having to manually create my own BeanInfo for it.
Maybe try this annotation from the beans API: http://download.oracle.com/javase/7/docs/api/java/beans/Transient.html
They advice you to actually place it on the getter, so that seems to fit the bill.
EDIT: oops, just noticed this was introduced in Java 7. So you're gonna need to make sure this runs in a very recent JRE if you want to use it.
Greetings,
I am currently trying to learn some Java programming. To do this I'm trying to make something actually useful. Because I'm studying Medical Imaging, I though I would write my own Dicom Api in Java.
Part of the Dicom Standard is a Data Dictionary containing attributes used in Dicom Files. These attributes have to following properties.
(Group,Element) Description
For example:
(0x0002,0x0000) Length
(0x0002,0x0002) MediaStoredSOPClassUID
(0x0002,0x0010) TransferSyntaxUID
(0x0003,0x0003) Length
I was wondering how I should implement these in my API. The options I have thought of are:
Enum, problem with that is that unique attributes could have the same description.
enum Attributes{
Length(0x0002,0x0000),
Length(0x0003,0x0000,
}
A static class with just some constants containing the properties. Also the problem with the names excists.
A xml file containing this data.
I really would like to use xml for this, because of the tabularity of the data and easy access. But is there any way I can include this in my Api.
~Timo Willemsen
To ease the access, the XML file should be placed in the classpath so that you can get its location by ClassLoader#getResource() or its contents by ClassLoader#getResourceAsStream().
To read/evaluate/write the XML file with a standard API, I can recommend StAX. If the XML file is relatively large (over tens of megabytes), then I can recommend VTD-XML more.
Alternatively, if the file is not so large and it are pure key-value pairs, then you can also consider properties files, which you can easily manage with java.util.Properties API which basically extends Map.
a map will work best for you, define a class that will hold a dicom entry :
public class DicomEntry
{
private:
private string group;
private string element;
private string vr;
private string name;
public string key() { return String.format("(%s,%s)",group,element); }
}
also create a map that will hold all the entries
Map<string,DicomEntry> mp=new HashMap<string, DicomEntry>();
after reading each line from your dictionary file into an entry class object de add it the map
mp.put(de.key(), de)
since the combination of group and element is unique you wound have any collisions
You might also want to study other DICOM sources. PixelMed, in particular, contains an XML and XSLT based validator. Several DICOM plugins are available for ImageJ.
Here is PS 3.6-2008 as XML as used in GDCM:
http://gdcm.svn.sf.net/viewvc/gdcm/trunk/Source/DataDictionary/Part6.xml?view=markup
As mentionned above, I would also add VM and Retired flag:
public class DicomEntry { private:
private ushort group;
private ushort element;
private string vr;
private string vm;
private boolean retired;
private string name;
public string key() { return String.format("(%s,%s)",group,element);
} }