I need to convert this String to POJO. Pls tel me how can i do this
This is Just an example
Anne12F02PhysicsPassChemistryPassFirstClass
This is the string.. Now i need to convert this to pojo
My POJO looks like this
Class student {
String Name;
int age;
char sex;
List<Subject> subList;
String classiness;
}
Class subject {
String subject;
String result;
}
This is just an example.
02 in the string indicates the size of list.
Note :: And also the length of each attribute is predefined(example.. Name 10 chars.. if there are only 5 chars in th开发者_如何学JAVAe name, then blank space is appended)
The list may again contain a list, the length will be indicated
If the lengths of the attributes are predefined, you could just use method String.substring(int, int)
to retrieve each attribute, and then create the POJO out of the parsed values. Something like following code snippet:
String input = "Anne12F02PhysicsPassChemistryPassFirstClass";
String name = input.substring(0, NAME_LENGTH); // name length is predefined
String age = input.substring(NAME_LENGTH, NAME_LENGTH + AGE_LENGTH);
// and so on
Student s = new Student(name, Integer.parseInt(age));
You need to use substring on the String to get all the different elements. You will then need to use Integer.parseInt
and similar functions to convert the string to the types you need, and then finally, construct your POJO with the calculated variables.
Also, if one of the elements is a list (which it is), then you will need to create an ArrayList and add each element, depending on the size of the list that needs parsing.
So, a sample would be (assume your input string is called toPojo
)
String name = toPojo.substring(0, 10);
int age = Integer.parseInt(toPojo.substring(10, 12));
As this is homework, try finishing the rest off...
EDIT: Follow up
to get the list, do something like
// get size of list and loop from zero to the size of the list
// find the index of the first item in the list
// int index = startIndex + loop*itemLength
// toPojo.substring(index, index+sizeOfElement);
If your strings have variable length, you might want to write the string length before the string itself, or use some delimiters between the fields, say commas or pipeline characters.
精彩评论