Untitled
unknown
plain_text
a year ago
6.2 kB
4
Indexable
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
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 values without quotes as well (like numbers or booleans)
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;
}
}
}
}
} 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));
}
} 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");
}
}
class Person extends Base {
private String name;
private int age;
// 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;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class Main {
public static void main(String[] args) {
String json = "{\"Name\": \"John\", \"Age\": 33}";
Person person = new Person();
person.fromJSON(json);
System.out.println(person); // Output: Person{name='John', age=33}
// Another example with booleans and doubles
String json2 = "{\"Name\": \"Alice\", \"Age\": 28, \"IsEmployed\": true, \"Salary\": 55000.50}";
Person person2 = new Person();
person2.fromJSON(json2);
System.out.println(person2); // Output: Person{name='Alice', age=28}
}
}
Editor is loading...
Leave a Comment