JSON to XML with multiple records - java

I am newbie in JAVA and trying to convert JSON data format to XML for multiple records. The result is not a well defined XML structure.The below code is working fine when a single record of item exists.
{
"items": [
{
"item": {
"ID": "79C675F752491945E1A",
"Subject": "test1 ",
"Sender": "user1",
"Date": "2014-07-14 14:14:40",
"DocumentClassID": "1",
"Comment": "",
}
},
{
"item": {
"ID": "79C67761945E1A",
"Subject": "test2",
"Sender": "user2",
"Date": "2014-07-14 14:14:40",
"DocumentClassID": "1",
"Comment": "",
}
}
]
}
===================Code Snippet=============================
public class ConvJsonXml extends AbstractTransformation {
public void transform(TransformationInput in, TransformationOutput out) throws StreamTransformationException {
try {
String sourcexml = ""; String targetxml =""; String line ="";
InputStream ins = in.getInputPayload().getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader(ins));
while ((line = br.readLine()) != null)
sourcexml +=line+"\n";
br.close();
JSONObject o = new JSONObject(sourcexml);
targetxml = org.json.XML.toString(o);
out.getOutputPayload().getOutputStream().write(targetxml.getBytes());
}
catch (Exception e) {
throw new StreamTransformationException(e.getMessage());
}
}
}
Please suggest me to add code in the Try block so that the conversion provides a well uniform XML structure.
Regards..

Related

I want to add a new Object inside a Json Object in JAVA with JSONObject

Im trying to make a JAVA application that makes a json file with the data that i send, but when i send new data, the last data the data is just replaced
the first method called
az.addUser("John", "10", "star");
the JSON
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
}
second method called
az.addUser("Kevin", "20", "energy");
The JSON Expected
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "energy"
}
}
the REAL JSON
{
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "Energy"
}
}
The Method
public void addUser(String name, String score, String type){
FileWriter wf = new FileWriter("exit.json");
JSONObject json;
JSONObject jsonInternal = new JSONObject();
jsonInternal.put("name", name);
jsonInternal.put("score", score);
jsonInternal.put("type", type);
json = new JSONObject();
json.put("user", jsonInternal);
wf.write(json.toJSONString());
wf.close();
}
You need to write a JSON array, not a JSON object. The code below is strictly pseudocode, as I do not know which library JSONObject comes from.
import java.io.FileWriter;
import java.io.IOException;
public class UserListWriter {
private String filename;
private JSONArray usersJson;
public UserListWriter(String filename) {
this.filename = filename;
this.usersJson = new JSONArray();
}
public UserListWriter addUser(String name, int score, String type) {
JSONObject userJson = new JSONObject();
userJson.put("name", name);
userJson.put("score", score);
userJson.put("type", type);
usersJson.put(userJson);
return this;
}
public UserListWriter write() throws IOException {
FileWriter wf = new FileWriter(this.filename);
wf.write(usersJson.toJSONString());
wf.close();
return this;
}
public static void main(String[] args) {
try {
new UserListWriter("exit.json")
.addUser("John", 10, "star")
.addUser("Kevin", 20, "energy")
.write();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Theoretical output:
[{
"name": "John",
"score": 10,
"type": "star"
}, {
"name": "Kevin",
"score": 20,
"type": "energy"
}]

Bulk Upload/Import of JSON files to Azure Cosmos DB from Java Code

I'm generating a JSON file in JAVA. The file contains a list of JSONs. I want to import this file to Azure Cosmos DB as soon as it is created.
Is there some way to achieve it from Java code?
Thanks in advance!
According to my research, if we want to implement bulk operations with java, we just can use bulk executor Java library. For more details, please refer to the document and article. Regarding how to use bulk executor Java library, please refer to the document.
For example
My .json file
[{
"id": "1",
"name": "test1",
"age": "20"
}, {
"id": "2",
"name": "test2",
"age": "21"
}, {
"id": "3",
"name": "test3",
"age": "22"
}, {
"id": "4",
"name": "test4",
"age": "23"
},
{
"id": "5",
"name": "test5",
"age": "24"
}, {
"id": "6",
"name": "test6",
"age": "25"
}, {
"id": "7",
"name": "test7",
"age": "26"
}, {
"id": "8",
"name": "test8",
"age": "27"
}
]
My pom.xml
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>documentdb-bulkexecutor</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Code
String endpoint="<your cosmos db endpoint>";
String key="<your key>";
ConnectionPolicy connectionPolicy = new ConnectionPolicy();
connectionPolicy.setMaxPoolSize(1000);
DocumentClient client = new DocumentClient(
endpoint,
key,
connectionPolicy,
ConsistencyLevel.Session);
String databaseId="testbulk";
String collectionId="items";
String databaseLink = String.format("/dbs/%s", databaseId);
String collectionLink = String.format("/dbs/%s/colls/%s", "testbulk", collectionId);
ResourceResponse<Database> databaseResponse = null;
Database readDatabase = null;
try {
databaseResponse = client.readDatabase(databaseLink, null);
readDatabase = databaseResponse.getResource();
System.out.println("Database already exists...");
} catch (DocumentClientException dce) {
if (dce.getStatusCode() == 404) {
System.out.println("Attempting to create database since non-existent...");
Database databaseDefinition = new Database();
databaseDefinition.setId(databaseId);
client.createDatabase(databaseDefinition, null);
databaseResponse = client.readDatabase(databaseLink, null);
readDatabase = databaseResponse.getResource();
} else {
throw dce;
}
}
ResourceResponse<DocumentCollection> collectionResponse = null;
DocumentCollection readCollection = null;
try {
collectionResponse = client.readCollection(collectionLink, null);
readCollection = collectionResponse.getResource();
System.out.println("Collection already exists...");
} catch (DocumentClientException dce) {
if (dce.getStatusCode() == 404) {
System.out.println("Attempting to create collection since non-existent...");
DocumentCollection collectionDefinition = new DocumentCollection();
collectionDefinition.setId(collectionId);
PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition();
Collection<String> paths = new ArrayList<String>();
paths.add("/id");
partitionKeyDefinition.setPaths(paths);
collectionDefinition.setPartitionKey(partitionKeyDefinition);
RequestOptions options = new RequestOptions();
options.setOfferThroughput(1000000);
// create a collection
client.createCollection(databaseLink, collectionDefinition, options);
collectionResponse = client.readCollection(collectionLink, null);
readCollection = collectionResponse.getResource();
} else {
throw dce;
}
}
System.out.println(readCollection.getId());
System.out.println(readDatabase.getId());
ArrayList<String> list = new ArrayList<String>();
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("e:\\test.json")) {
//Read JSON file
Object obj = jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) obj;
System.out.println(jsonArray);
// cast jsonarry to string list
if (jsonArray != null) {
int len = jsonArray.size();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
System.out.println(list.get(0));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
// Set client's retry options high for initialization
client.getConnectionPolicy().getRetryOptions().setMaxRetryWaitTimeInSeconds(30);
client.getConnectionPolicy().getRetryOptions().setMaxRetryAttemptsOnThrottledRequests(9);
// Builder pattern
DocumentBulkExecutor.Builder bulkExecutorBuilder = DocumentBulkExecutor.builder().from(
client,
databaseId,
collectionId,
readCollection.getPartitionKey(),
20000) ;// throughput you want to allocate for bulk import out of the container's total throughput
// Instantiate DocumentBulkExecutor
try {
DocumentBulkExecutor bulkExecutor = bulkExecutorBuilder.build();
// Set retries to 0 to pass complete control to bulk executor
client.getConnectionPolicy().getRetryOptions().setMaxRetryWaitTimeInSeconds(0);
client.getConnectionPolicy().getRetryOptions().setMaxRetryAttemptsOnThrottledRequests(0);
BulkImportResponse bulkImportResponse = bulkExecutor.importAll(list, false, false, null);
System.out.println(bulkImportResponse.getNumberOfDocumentsImported());
} catch (Exception e) {
e.printStackTrace();
}

Android Json data parsing is ''[]'',Data parsing failed

Recently, I tried to code a list of linkman. I want to obtaining local data file(City.json) and parsing into listView. However ,the data from JsonObject always null. Help me please. I'm a Newbie. Thanks in advance.
the code under:
City.json
{
// "state": 1,
"datas": [
{
"id": "820",
"name": "安阳",
"sortKey": "A"
},
{
"id": "68",
"name": "安庆",
"sortKey": "A"
},
{
"id": "1269",
"name": "鞍山",
"sortKey": "A"
},
{
"id": "22",
"name": "蚌埠",
"sortKey": "B"
},
{
"id": "1372",
"name": "包头",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
}
]
}
AppFileReader.java
package me.sitinglin.administrator.wecharlinkmantest;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
/**
* Created by Administrator on 2016/10/12.
*/
public class AppJsonFileReader {
public static String getJson(Context context, String fileName){
StringBuilder builder = new StringBuilder();
AssetManager manager = context.getAssets();
try {
InputStream stream = manager.open(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line = null;
while((line = bufferedReader.readLine())!=null){
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Log.i("abc", builder.toString());
return builder.toString();
}
public static List<City> setData(String str){
List<City> list = new ArrayList<>();
City city ;
try {
JSONObject result = new JSONObject(str);
JSONArray array = result.getJSONArray("datas");
// JSONArray array =new JSONArray(result);
int len = array.length();
Log.i("len", array.toString());
for (int i = 0; i <len ; i++) {
JSONObject object = array.optJSONObject(i);
city = new City();
city.setId(object.optString("id"));
city.setName(object.optString("name"));
city.setSortKey(object.optString("sortKey"));
list.add(city);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("lll", list.toString());
return list;
}
}
this my context of logcat
Try this:
try {
JSONObject result = new JSONObject(str);
JSONArray jsonArray = result.getJSONArray("datas");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
city = new City();
city.setId(object.optString("id"));
city.setName(object.optString("name"));
city.setSortKey(object.optString("sortKey"));
list.add(city);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("lll", list.toString());
return list;
You should go with following code :
JSONObject jobj = new JSONObject(str);
if(jobj.has("datas")){
JSONArray jsonArray = jobj.getJSONArray("datas");
List<City> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jdataObj = jsonArray.getJSONObject(i);
City city = new City();
city.setId(jdataObj.getString("id"));
city.setName(jdataObj.getString("name"));
city.setSortKey(jdataObj.getString("sortKey"));
list.add(city);
}
} else {
Log.e("Json","Json has no datas key.")
}
Hope this will help you.
I found 3 solution to solve this.i will list 3 things that i've solved below and one of the 3 solutions may helped you.
there are three point which one of three point maybe help U :
1. checking out the [local file name] of JSON;
2. checking out variale is "public " or "private"..;
3.checking out some Json method whether you are uesing correct?
Aha...

Retrieving string from nested objects in JSON file || Android

I'm having trouble trying to access certain values in a JSON file.
The file has multiple objects stored inside an array.
The value I need to return is "60" inside the "maxspeed" string.
When the current code is executed in debug it just remains in a loop.*Not sure why)
The value of the "result" string is the entire json file.
Would anyone be able to explain how to access this value?
Thanks.
JSON:
{
"version": 0.6,
"generator": "Overpass API",
"osm3s": {
"timestamp_osm_base": "2015-03-16T00:27:03Z",
"copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
},
"elements": [
{
"type": "node",
"id": 768053039,
"lat": 54.9526671,
"lon": -7.7273348
},
{
"type": "node",
"id": 768053040,
"lat": 54.9498094,
"lon": -7.7176056
},
{
"type": "node",
"id": 768053041,
"lat": 54.9497066,
"lon": -7.7173174
},
{
"type": "node",
"id": 768053043,
"lat": 54.9495658,
"lon": -7.7170937
},
{
"type": "node",
"id": 768053044,
"lat": 54.9495035,
"lon": -7.7169816
},
{
"type": "node",
"id": 791492493,
"lat": 54.9494183,
"lon": -7.7168205
},
{
"type": "node",
"id": 795319854,
"lat": 54.9510427,
"lon": -7.7218262
},
{
"type": "node",
"id": 795320324,
"lat": 54.9509153,
"lon": -7.7213706
},
{
"type": "node",
"id": 1922546572,
"lat": 54.9502165,
"lon": -7.7190169
},
{
"type": "node",
"id": 1922546679,
"lat": 54.9504739,
"lon": -7.7199078
},
{
"type": "node",
"id": 1922546692,
"lat": 54.9500860,
"lon": -7.7185174
},
{
"type": "node",
"id": 1922602861,
"lat": 54.9517250,
"lon": -7.7241644
},
{
"type": "node",
"id": 1922622063,
"lat": 54.9514357,
"lon": -7.7231690
},
{
"type": "node",
"id": 2673934802,
"lat": 54.9498543,
"lon": -7.7177617
},
{
"type": "way",
"id": 64273241,
"nodes": [
768053039,
1922602861,
1922622063,
795319854,
795320324
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
},
{
"type": "way",
"id": 64887990,
"nodes": [
795320324,
1922546679,
1922546572,
1922546692,
2673934802,
768053040,
768053041,
768053043,
768053044,
791492493
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
}
]
}
Code:
protected Void doInBackground(String... params) {
android.os.Debug.waitForDebugger();
//String url_select = "http://yoururlhere.com";
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(encode2);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line); } }
else {
Log.e("==>", "Failed to download file"); }
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); }
result = builder.toString();
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONObject parentObject = new JSONObject(result);
JSONArray speedJSON = parentObject.getJSONArray("elements");
JSONObject maxspeed = parentObject.getJSONObject("maxspeed");
System.out.print(""+maxspeed.toString()+"\n");
//String[] elementNames = JSONObject.(speedJSON);
System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", speedJSON.length());
for (int i = 0; i< speedJSON.length(); i++)
{
String value = speedJSON.getString(i);
System.out.printf("name=%s, value=%s\n", speedJSON.get(i), value);
}
//And then read attributes like
/* for(int i = 0; i<speedJSON.length(); i++){
JSONObject child = speedJSON.getJSONObject(i);
if(child.getString("type").equals("way")){
JSONObject tag = speedJSON.getJSONObject(i);
JSONObject maxspeed = tag.getJSONObject("tags");
String speed = maxspeed.getString("maxspeed");
txtSpeed.setText(speed);
}
}*/
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* try {
JSONArray jArray = new JSONArray(result);
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String speedLimit = jObject.getString("maxspeed");
txtSpeed.setText(speedLimit);
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
*/ } // protected void onPostExecute(Void v)
}
Okay your first problem is that not all JSONObjects from your "elements" array have a max speed property. The second problem is that you are not iterating over your JSONArray correctly.
Lets start with the second proble:
for (int i = 0; i < speedJSON.length(); i++) {
JSONObject element = (JSONObject) speedJSON.get(i);
}
Now your element is the JSONObject which contains your different properties (type, id, lon, ...)
To solve your first problem you can check if a JSONObject contains the key you are looking for (maxspeed)
if (!element.isNull("tags") {
JSONObject tags = (JSONObject)element.get("tags");
if (!tags.isNull("maxspeed") {
String maxspeed = tags.getString("maxspeed");
}
} else {
//Your error handling here...
}
Hope this helps!

Parse a nested JSON using gson

{
"Response": {
"MetaInfo": {
"Timestamp": "2011-11-21T14:55:06.556Z"
},
"View": [
{
"_type": "SearchResultsViewType",
"ViewId": 0,
"Result": [
{
"Relevance": 0.56,
"MatchQuality": {
"Country": 1,
"State": 1,
"County": 1,
"City": 1,
"PostalCode": 1
},
"Location": {
"LocationType": "point",
"DisplayPosition": {
"Latitude": 50.1105,
"Longitude": 8.684
},
"MapView": {
"_type": "GeoBoundingBoxType",
"TopLeft": {
"Latitude": 50.1194932,
"Longitude": 8.6699768
},
"BottomRight": {
"Latitude": 50.1015068,
"Longitude": 8.6980232
}
},
"Address": {
"Country": "DEU",
"State": "Hessen",
"County": "Frankfurt am Main",
"City": "Frankfurt am Main",
"District": "Frankfurt am Main",
"PostalCode": "60311",
"AdditionalData": [
{
"value": "Germany",
"key": "CountryName"
}
]
}
}
}
]
}
]
}
}
I am trying to retrieve the postal code from the above JSON. I am using gson to parse it. I am very new to JSON and from what i read from all the posts here(some very similar to this), I understood that the fields name should be as it is. So I understand i have to make 4 classes viz Response, view, Result and Address. I made them static nested classes, but I am only getting null value as output. In the next JSON, I have multiple addresses. But I am stuck on this single response.
For a short example, I try to retrieve Timestamp with this code, but it gives me a null value
public class ParseJSON {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("try.json"));
Gson gson = new GsonBuilder().create();
Pojo pojo = gson.fromJson(br,Pojo.class);
System.out.println(Pojo.Response.MetaInfo.Timestamp);
br.close();
}
}
class Pojo {
public Pojo() { }
static class Response{
static class MetaInfo {
static public String Timestamp;
public String getTimestamp() {
return Timestamp;
}
}
}
}
If you only need the "PostalCode", you could use JsonParser instead of having a bunch of classes:
JsonParser jsonParser = new JsonParser();
JsonObject address = jsonParser.parse(json)
.getAsJsonObject().get("Response")
.getAsJsonObject().getAsJsonArray("View").get(0)
.getAsJsonObject().getAsJsonArray("Result").get(0)
.getAsJsonObject().get("Location")
.getAsJsonObject().getAsJsonObject("Address");
String postalCode = address.get("PostalCode").getAsString();
or for all results:
JsonArray results = jsonParser.parse(json)
.getAsJsonObject().get("Response")
.getAsJsonObject().getAsJsonArray("View").get(0)
.getAsJsonObject().getAsJsonArray("Result");
for (JsonElement result : results) {
JsonObject address = result.getAsJsonObject().get("Location").getAsJsonObject().getAsJsonObject("Address");
String postalCode = address.get("PostalCode").getAsString();
System.out.println(postalCode);
}
To make your Timestamp example work, try:
public class ParseJSON {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("try.json"));
Gson gson = new GsonBuilder().create();
Pojo pojo = gson.fromJson(br, Pojo.class);
System.out.println(pojo.Response.MetaInfo.Timestamp);
br.close();
}
}
class Pojo {
Response Response = new Response();
}
class Response {
MetaInfo MetaInfo = new MetaInfo();
}
class MetaInfo {
String Timestamp;
}

Categories