Im doing a RESTful webservice call on the Chinese weibo platform and get a JSON file in return that looks like this:
[{
"id": 2098220080,
"idstr": "2098220080",
"class": 1,
"screen_name": "王理巍", .....}]
So its an array with 100 inner objects. My aim is to import these data into a relational database (SAP HANA). As I can only import files in XML or csv format, I think the best approach is to parse the JSON into XML with some small java app. Ive already tried different JSON parsing libraries but there seems to be a problem with the array. So I chose the Apache json.org lib and call the webservice via InputStream.
public static void main(String[] args) throws IOException {
String date, userName = null, text, gender, city, location, province;
int userId = 0, statusId;
URL url = null;
try {
url = new URL("https://api.weibo.com/2/suggestions/users/hot.json?client_id=1637521539&access_token=2.00xusAWD0YuxsZ10f9689fa7sIoHJC&category=auto");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Call URL as InputStream
try (InputStream is = url.openStream();
JsonReader rdr = Json.createReader(is)) {
JsonArray results = rdr.readArray();
//System.out.println(results.toString());
JsonObject[] objects = new JsonObject[100];
JsonObject o1 = results.getJsonObject(0);
//System.out.println(o1);
//Read each element
try {
userId = o1.getInt("id");
userName = o1.getString("name");
province = o1.getString("province");
city = o1.getString("city");
location = o1.getString("location");
gender = o1.getString("gender");
date = o1.getString("created_at");
statusId = o1.getInt("id");
text = o1.getString("text");
} catch (NullPointerException npe) {
System.out.println("No value");
}
//Build XML
String xmlString = XML.toString(userId,"id");
xmlString = XML.toString(userName, "name");
In this snippet I only read one object for testing purposes without any automation. Basically Im dealing with 2 issues here now.
First: The elements containing Chinese simplified characters are displayed as ??? Second: How can I append several elements to the XML-String?
I really appreciate your hints concerning my questions and also some general ideas for a probable better solution.
Alright problems solved.
In case ur interested: To access the nested "status" element in one object, just use
JsonObject status = o1.getJsonObject("status");
For appending several objects I used the StringBuilder method.