I would like to convert XML to JSON.
Currently, I make this with the lib org.json :
JSONObject jso = XML.toJSONObject(xmlStr);
However, if the XML contains number fields, I would like to have only String fields in the JSONObject.
For example:
The XML file is :
<ID>3</ID>
<NAME>ApplicationName</NAME>
The org.json permits me to have:
{
"ID" : 3,
"Name" : "ApplicationName"
}
The final result has to be :
{
"ID" : "3",
"Name" : "ApplicationName"
}
I resolve mt problem by using the latest version of org.json.
There is a methode to do this :
JSONObject jso = XML.toJSONObject(xmlStr, true);
The boolean is using to keep the string fields.
Related
I need to read and parse a json array from java properties file. I'm able to read the properties file and get the json array String. But I'm unable to parse the json array and get the values. I'm using gson library. Here is the data from properties file
jsonarray = [ { key1 : value1, key2 : value2 } ]
Code:
Properties properties = new Properties();
properties.load(new FileInputStream(filePath));
String jsonArray = properties.getProperty("jsonarray")
JsonElement element = new JsonPrimitive(jsonArray);
JsonArray array = element.getAsJsonArray();
I'm getting IllegalStateException
java.lang.IllegalStateException: Not a JSON Array: "[ { key1 : value1, key2 : value2 } ]"
The problem is it is taking extra double quotes at the beginning and at the end.
I have tried adding quotes to keys and values, but with no success. I need to use gson library itself, so please don't suggest other libraries. I cannot create a POJO class for it and use new Gson().fromJson(jsonArray), so kindly please don't suggest that also.
I've searched and tried a lot without success. The method I referred is given here
Thanks in advance
Edit 1: I've tried the following in properties file
jsonarray = [ { "key1" : "value1", "key2" : "value2" } ]
and I got same exception like
java.lang.IllegalStateException: Not a JSON Array: "[ { \"key1\" : \"value1\", \"key2\" : \"value2\" } ]"
I tried to create a JsonArray object in code and print it
JsonArray array = new JsonArray();
JsonObject object = new JsonObject();
object.addProperty("key1", "value1");
object.addProperty("key2", "value2");
array.add(object);
System.out.println(array.toString());
The output was as below
[{"key1":"value1","key2":"value2"}]
The Javadoc of JsonPrimitive you've used here
JsonElement element = new JsonPrimitive(jsonArray);
states
Create a primitive containing a String value.
When you then do
JsonArray array = element.getAsJsonArray();
it'll obviously fail because element is a JSON String, not a JSON array. Just parse the JSON directly
JsonArray array = new Gson().fromJson(jsonArray, JsonArray.class)
This is all after you've changed your properties file content to be actual JSON
jsonarray = [ { "key1" : "value1", "key2" : "value2" } ]
I have a JSON file which I read from a location and converted it into string as below i.e. A string variable contains exact same JSON as printed below. For some testing purpose I needed it.
So the thing is that I want to update the value of key "MainId". How do I do that?
Here is mine JSON:
{
"Entity": {
"MainId":"XFG",
"AlternateIdentifiers" : [
{
"Type":{
"Abbreviation":"ReferenceNumber"
},
"Value":"abc"
}
]
}
}
Initialize a JSONObject , you have to import the json.org library , put the json in a string and then in the constructor of JSONObject.
So you can navigate the JSON through this new object.
Given this POJO:
public class People {
String sex;
long age;
String names;
}
The "names" property will be a json string for which I need to create nested documents for. Here is an example of an instance I need to save to Elasticsearch using Jest Client:
People people = new People();
people.setSex("Male");
people.setAge(21);
people.setNames("[{\"fname\": \"Bob\",\"lname\": \"Smith\"},[{\"fname\": \"Mike\",\"lname\": \"Johnson\"}");
Index index = new Index.Builder(people).index("indexName").type("aType").build();
jestClient.execute(index);
The result document in ES looks like:
"_source" : {
"sex" : "Male",
"age" : 21,
"names" : "[{\"fname\": \"Bob\",\"lname\": \"Smith\"},{\"fname\": \"Mike\",\"lname\": \"Johnson\"}]"
}
So it took the String names and inserted it as a literal String, which makes sense but I actually need to create documents from each name object. In other words I want it to look like this:
"_source" : {
"sex" : "Male",
"age" : 21,
"names" : [{
"fname": "Bob",
"lname": "Smith"
}, {
"fname": "Mike",
"lname": "Johnson"
}]
}
I tried adding a mapping to tell ES to treat it as "nested" but then I get a Mapper Parsing Exception saying "tried to parse field [names] as object, but found a concrete value".
I know I should be able to do this if I create an actual Name POJO object and have a list of them, but unfortunately due to requirements I am unable to do this. I have to use the string of JSON provided in the format specified above.
SOLUTION:
Thanks to Vishal Rao for pointing me in the right direction.
The solution was to change the "names" type to a JsonArray (Google GSON). Then used the Google GSON parser as such:
People people = new People();
people.setSex("Male");
people.setAge(21);
String json = "[{\"fname\": \"Bob\",\"lname\": \"Smith\"},[{\"fname\": \"Mike\",\"lname\": \"Johnson\"}"
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(json);
JsonArray jsonArray = jsonElement.getAsJsonArray();
people.setNames(jsonArray);
Index index = new Index.Builder(people).index("indexName").type("aType").build();
jestClient.execute(index);
In addition I also have a mapping that sets the names property to a nested type.
You might want to try converting your string to a JSON object first, that's probably why you're getting that error. Elasticsearch tries to parse it as an object but finds a string there instead.
Maybe do something like:
JSONObject jsonObj = new JSONObject(names);
and then using that object.
So I have a JSON object that looks like this:
{
"accessToken" : "<dont need this>",
"clientToken" : "<nor this>",
"selectedProfile" : {
"id" : "<nope>",
"name" : "<I need this>",
"legacy" : true
},
"availableProfiles" :
[
{
"id" : "<not this>",
"name" : "<not this>",
"legacy" : true
}
]
}
So what I need is selectedProfile > name. I am able to extract selected profiles, would I just repeat the process on that? What should I do to retrieve it?
Using javax.json
JsonReader reader = new JsonReader(yourString);
JsonObject base = reader.readObject();
JsonObject profile = base.getJsonObject("selectedProfile");
String name = profile.getJsonString("name");
and then name should be the object you want.
Try this:
String name = yourJSON.getJSONObject("selectedProfile").getString("name").toString();
I'm using the package org.json to parse a JSONArray (I have the json strings saved in a database). However, I don't succeed in parsing it when the same key could have associated a String or a JSONObject, depending on the context.
For example, see the following JSON code...
[ { "cssClass" : "input_text",
"required" : "undefined",
"values" : "First Name"
},
{ "cssClass" : "checkbox",
"required" : "undefined",
"title" : "What's on your pizza?",
"values" : { "2" : { "baseline" : "undefined",
"value" : "Extra Cheese"
},
"3" : { "baseline" : "undefined",
"value" : "Pepperoni"
}
}
}
]
In the code above, the key "values" has 2 possibilities...
A String with value "First Name"
A JSONObject with value {"2":{"value":"Extra Cheese","baseline":"undefined"},"3":{"value":"Pepperoni","baseline":"undefined"}}.
How am I able to process this correctly when the value could be 2 different data types?
You'll probably still need to detect whether it is a JSONObject or a String, so that you can process it further, but perhaps something here might help...
You could try something like this...
String cssClass = myJson.getString("cssClass");
if (cssClass.equals("input_text")){
// Read it as a String
String values = myJson.getString("values");
}
else if (cssClass.equals("checkbox")){
// Read it as a JSONObject
JSONObject values = myJson.JSONObject("values");
// further processing here
}
Or maybe something like this...
String cssClass = myJson.getString("cssClass");
String values = myJson.getString("values");
if (cssClass.equals("input_text")){
// do nothing - it's already a String
}
else if (cssClass.equals("checkbox")){
// Parse the String into a JSONObject
JSONObject valuesObject = new JSONObject(values);
// further processing here
}
Think it this way in js or java duplicate variable creation under same scope is invalid,so to avoid ambiguity put them in separate json object with different variable names before putting it to the json array.