Untitled
unknown
plain_text
a year ago
9.3 kB
9
Indexable
import java.lang.reflect.Method;
import java.util.*;
public class Base {
// The fromJSON method that parses the JSON and sets the values
public void fromJSON(String json) {
try {
// Manually parse the JSON string into a map of field names and values
Map<String, String> fields = parseJSON(json);
// Iterate through the fields and find matching setters using reflection
for (Map.Entry<String, String> entry : fields.entrySet()) {
String fieldName = entry.getKey();
String fieldValue = entry.getValue();
// Find the setter method corresponding to this field
String setterMethodName = "set" + capitalize(fieldName);
Method setterMethod = findSetterMethod(setterMethodName, fieldValue);
if (setterMethod != null) {
// Invoke the setter method with the appropriate value
invokeSetter(setterMethod, fieldValue);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Manually parse the JSON string into a Map<String, String>
private Map<String, String> parseJSON(String json) {
Map<String, String> fields = new HashMap<>();
// Remove surrounding curly braces and trim the string
json = json.trim().substring(1, json.length() - 1).trim();
// Split the JSON string into key-value pairs
String[] keyValuePairs = json.split(",\\s*");
// Loop through the pairs and extract key-value
for (String pair : keyValuePairs) {
String[] keyValue = pair.split(":\\s*");
String key = keyValue[0].trim().replaceAll("\"", ""); // Remove quotes around key
String value = keyValue[1].trim().replaceAll("\"", ""); // Remove quotes around value
// Handle arrays in JSON values
if (value.startsWith("[") && value.endsWith("]")) {
fields.put(key, value);
} else {
fields.put(key, value);
}
}
return fields;
}
// Capitalizes the first letter of a string (helper method for setter name matching)
private String capitalize(String fieldName) {
return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
}
// Find a matching setter method using reflection
private Method findSetterMethod(String setterMethodName, String fieldValue) {
try {
// Check for setter methods in the current class
for (Method method : this.getClass().getMethods()) {
if (method.getName().equals(setterMethodName)) {
if (method.getParameterCount() == 1) {
// Match based on the parameter type
Class<?> paramType = method.getParameterTypes()[0];
if (paramType.equals(String.class)) {
return method;
} else if (paramType.equals(int.class) && isInteger(fieldValue)) {
return method;
} else if (paramType.equals(double.class) && isDouble(fieldValue)) {
return method;
} else if (paramType.equals(boolean.class) && isBoolean(fieldValue)) {
return method;
} else if (paramType.equals(String[].class) && isArrayOfStrings(fieldValue)) {
return method;
} else if (paramType.equals(int[].class) && isArrayOfIntegers(fieldValue)) {
return method;
}
// Handle arrays of objects
else if (paramType.isArray() && paramType.getComponentType().equals(Object.class)) {
return method;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// Invokes the setter method dynamically using reflection
private void invokeSetter(Method setterMethod, String fieldValue) {
try {
Class<?> paramType = setterMethod.getParameterTypes()[0];
if (paramType.equals(String.class)) {
setterMethod.invoke(this, fieldValue);
} else if (paramType.equals(int.class)) {
setterMethod.invoke(this, Integer.parseInt(fieldValue));
} else if (paramType.equals(double.class)) {
setterMethod.invoke(this, Double.parseDouble(fieldValue));
} else if (paramType.equals(boolean.class)) {
setterMethod.invoke(this, Boolean.parseBoolean(fieldValue));
} else if (paramType.equals(String[].class)) {
setterMethod.invoke(this, parseStringArray(fieldValue));
} else if (paramType.equals(int[].class)) {
setterMethod.invoke(this, parseIntArray(fieldValue));
}
// Handle arrays of objects
else if (paramType.isArray()) {
setterMethod.invoke(this, parseObjectArray(paramType, fieldValue));
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Helper method to check if a string represents an integer
private boolean isInteger(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
// Helper method to check if a string represents a double
private boolean isDouble(String value) {
try {
Double.parseDouble(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
// Helper method to check if a string represents a boolean
private boolean isBoolean(String value) {
return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false");
}
// Helper method to check if a string represents an array of strings
private boolean isArrayOfStrings(String value) {
return value.startsWith("[") && value.endsWith("]");
}
// Helper method to check if a string represents an array of integers
private boolean isArrayOfIntegers(String value) {
return value.startsWith("[") && value.endsWith("]") && value.matches("\\[\\d+(,\\s*\\d+)*\\]");
}
// Parse a string array from the JSON representation
private String[] parseStringArray(String value) {
value = value.substring(1, value.length() - 1); // Remove brackets
return value.split(",\\s*");
}
// Parse an int array from the JSON representation
private int[] parseIntArray(String value) {
value = value.substring(1, value.length() - 1); // Remove brackets
String[] parts = value.split(",\\s*");
int[] result = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
result[i] = Integer.parseInt(parts[i]);
}
return result;
}
// Parse an array of objects from the JSON representation (simplified)
private Object[] parseObjectArray(Class<?> arrayType, String value) {
// Simplified for handling arrays of objects
value = value.substring(1, value.length() - 1); // Remove brackets
String[] parts = value.split(",\\s*");
Object[] result = new Object[parts.length];
for (int i = 0; i < parts.length; i++) {
try {
// Assuming the array holds strings for simplicity here
result[i] = parts[i]; // Could be customized for different object types
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
}
// Example Person class
class Person extends Base {
private String name;
private int age;
private String[] tags; // Array of strings
private int[] numbers; // Array of integers
// Getter and Setter methods
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getTags() {
return tags;
}
public void setTags(String[] tags) {
this.tags = tags;
}
public int[] getNumbers() {
return numbers;
}
public void setNumbers(int[] numbers) {
this.numbers = numbers;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + ", tags=" + Arrays.toString(tags) + ", numbers=" + Arrays.toString(numbers) + "}";
}
}
public class Main {
public static void main(String[] args) {
// Example JSON with arrays
String json = "{\"Name\": \"John\", \"Age\": 33, \"Tags\": [\"developer\", \"gamer\"], \"Numbers\": [1, 2, 3]}";
Person person = new Person();
person.fromJSON(json);
System.out.println(person); // Output: Person{name='John', age=33, tags=[developer, gamer], numbers=[1, 2, 3]}
}
}
Editor is loading...
Leave a Comment