Generate Java Class from JSON

How to create JAVA object from JSON string?

You can use the following way.

gson.toJson(obj); // is used to convert object to JSON

if you want to convert JSON to Java Object then you can use

gson.fromJson(json, Car.class);

Ex.

     public class Car {
public String brand = null;
public int doors = 0;
// add getter and setter

}

String json = "{\"brand\":\"Jeep\", \"doors\": 3}";

Gson gson = new Gson();

Car car = gson.fromJson(json, Car.class);

JSON to POJO: How to generate abstract java class names from unique JSON fields?

There is no standard way to parse situations like this(situations when you don't know field name). As an option you can manually parse your file using Jackson:

public void parseWikiResponse(String wikiResponse)  {
JsonFactory jsonFactory = new JsonFactory();

ObjectMapper mapper = new ObjectMapper(jsonFactory);

JsonNode jsonNodes = mapper.readTree(wikiResponse);

Iterator<Map.Entry<String,JsonNode>> fieldsIterator = jsonNodes.fields();

while (fieldsIterator.hasNext()) {

Map.Entry<String,JsonNode> field = fieldsIterator.next();

/* Here you can find your field with unknown name using regExp eg */
field.getKey();
}
}

If you want only for parsing this approach should solve the problem.

There is a similar question on this topic:

Parsing JSON in Java without knowing JSON format

Hope something helped (:



Related Topics



Leave a reply



Submit