import org.json.JSONObject;
import org.json.XML;
public class Example {
public static void main(String[] args) {
String xmlString = "<users><user name=test1 age=20></user><type><direct num=3></direct></type><report sub=eng score=30></report></users>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
System.out.println(jsonObject);
}
}
I can remove elements after conversion from xml to json. But actually what i needed is that, the elements or attributes should be removed during conversion itself.
My required output is:
{
"users": {
"report": {
"score": 30
},
"type": {
"direct": {
"num": 3
}
},
"user": {
"age": 20
}
}
}
XML class does not provide methods to exclude tags. One possible solution is update the string to remove tags as below,
e.g to exclude type tag,
String splits[] = xmlString.split("(<\\/type>|<type>)");
xmlString = splits[0]+splits[2];
JSONObject jsonObject = XML.toJSONObject(xmlString);
System.out.println(jsonObject);
Output:
{"users":{"report":{"sub":"eng","score":30},"user":{"name":"test1","age":20}}}
To remove name element from user tag,
String xmlString = "<users><user name=test1 age=20></user><type><direct num=3></direct></type><report sub=eng score=30></report></users>";
//split by user tags
String splits[] = xmlString.split("(<\\/user>|<user )");
//remove name filed and combine other elements
String user1 = Arrays.stream(splits[1].split(" "))
.filter(s->!s.contains("name"))
.collect(Collectors.joining(" "));
//merge strings and user tag
xmlString = splits[0] + "<user " + user1 + "</user>" + splits[2];
JSONObject jsonObject = XML.toJSONObject(xmlString);
Output::
{
"users": {
"report": {
"sub": "eng",
"score": 30
},
"type": {
"direct": {
"num": 3
}
},
"user": {
"age": 20
}
}
}
UPDATE:
The best solution would be to remove from JsonObject,
jsonObject.getJSONObject("users").getJSONObject("user").remove("name")
org.json.XML package doesn't provide internal XML modifications. If you must use this, you have to make the necessary modifications in the json by yourself. Else you can preprocess the xml using java default xml parser, convert it to string and then convert it to json.
Related
{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "XYZ",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
I am trying to update the "eventName" field with new String. I tried with the following code, It updates the field but returns only four fields in the json array.
public String modifyJson() throws Exception{
String jsonString = PiplineJson.payload(PiplineJson.filePath());
System.out.println(jsonString);
JSONObject jobject = new JSONObject(jsonString);
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
System.out.println(uu);
return uu;
}
This is what the above code does.
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
I am trying to get the complete json once it updates the eventName filed.
{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
The problem is the way that you are chaining the operations together. The problem is that you are calling toString() on the result of the put call. The put calls returns the inner JSONObject that it was called on. So you end up serializing the wrong object.
Changing this:
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
to
jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString());
String uu = jobject.toString();
should work.
That's because you are returning the first element you extracted from "places" array. You should return "jobject.toString()" instead.
Using Simple-JSON on the following JSON formatted file, I'm having a lot of trouble understanding how to access the objects within the array under "name".
JSON File:
[
{
"name":{
"firstName": "Developer",
"lastName": "D"
},
"id": 00,
"permissionLevel": 3,
"password": 12345
},
{
"name":{
"firstName": "Bob",
"lastName": "Smith"
},
"id": 01,
"permissionLevel": 2,
"password": 23456
}
]
I'm able to obtain the information for all of the other contents because they're not located in a nested array; However, when I attempt to retrieve the objects under "name", all that is output is the String found in the JSON file.
Current code:
String[] searchData = {
"name",
"firstName",
"lastName",
"id",
"permissionLevel",
"password"
};
jsonArray = (JSONArray)new JSONParser().parse(s);
for(int i = 0; i < jsonArray.size(); i++){
JSONObject jo = (JSONObject)jsonArray.get(i);
for(int j = 0; j < searchData.length; j++){
System.out.println(
searchData[j] + ": " + jo.get(searchData[j]));
}
}
Output:
name: [{"firstName":"Developer","lastName":"D"}]
firstName: null
lastName: null
id: 0
permissionLevel: 3
password: 12345
name: [{"firstName":"Bob","lastName":"Smith"}]
firstName: null
lastName: null
id: 1
permissionLevel: 2
password: 23456
As you can see, "name" outputs a String from the JSON file, and not each individual value.
In the end, I need to write a universal code that can accept new "searchData" tags for each file that's input.
Might someone be able to direct me how to obtain objects held
within nested arrays?
Or perhaps I need to use a different Library? If so, which one is the most efficient for Java? I'm not programming for Android, and I continue to find Library suggestions for Android, constantly.
My apologies if this post is a dupe, but no other posts are aiding me.
You should get your firstname and lastname, like:
jo.get("name").get("firstname");
jo.get("name").get("lastname");
To get the objects held within nested arrays/objects, you will have to write a recursive method and flatten the structure into a map. Below example shows the same:
public static void main(String args[]) throws ParseException {
Object object = new JSONParser().parse("[ { \"name\":{ \"firstName\": \"Developer\", \"lastName\": \"D\" }, \"id\": 00, \"permissionLevel\": 3, \"password\": 12345 }, { \"name\":{ \"firstName\": \"Bob\", \"lastName\": \"Smith\" }, \"id\":01, \"permissionLevel\": 2, \"password\": 23456 }]");
Map<String, Object> pairs = new HashMap<>();
addValues(object, pairs);
System.out.println(pairs);
}
public static void addValues(Object object, Map<String, Object> pairs){
if(object instanceof JSONObject){
JSONObject jsonObject = (JSONObject) object;
for(String key : jsonObject.keySet()){
if(jsonObject.get(key) instanceof JSONObject || jsonObject.get(key) instanceof JSONArray){
addValues(jsonObject.get(key), pairs);
}else{
pairs.put(key, jsonObject.get(key));
}
}
}else if(object instanceof JSONArray){
JSONArray jsonArray = (JSONArray)object;
for(Object element : jsonArray){
addValues(element, pairs);
}
}
}
You can tweak this method to have keys like name.firstname or name.lastname depending on requirements.
I understand that you want the searchData tags to be taken into consideration while parsing the JSON. I would suggest using Google Gson for this case.
You can write a POJO which return the ArrayList<User> for your JSON.
Refer this article on how use Google Gson
This question is related with my previous question
I can successfully get the String in json format from the URL to my spring controller
Now I have to decode it
so I did like the following
#RequestMapping("/saveName")
#ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
try
{
System.out.println(acc);
org.json.JSONObject convertJSON=new org.json.JSONObject(acc);
org.json.JSONObject newJSON = convertJSON.getJSONObject("nameservice");
System.out.println(newJSON.toString());
convertJSON = new org.json.JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("id"));
}
catch(Exception e)
{
e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
}
return jsonObject.toString();
}
This is the JSON String { "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
When I run the code then I get the error
org.json.JSONException: JSONObject["nameservice"] is not a JSONObject.
What wrong I am doing?
It's not a JSONObject, it's a JSONArray
From your question:
{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
The [ after the nameservice key tells you it's an array. It'd need to be a { to indicate an object, but it isn't
So, change your code to use it as a JSONArray, then iterate over the contents of that to get the JSONObjects inside it, eg
JSONArray nameservice = convertJSON.getJSONArray("nameservice");
for (int i=0; i<nameservice.length(); i++) {
JSONObject details = nameservice.getJSONObject(i);
// process the object here, eg
System.out.println("ID is " + details.get("id"));
System.out.println("Name is " + details.get("name"));
}
See the JSONArray javadocs for more details
It seems you're trying to get a JSONObject when "nameservice" is an array of JSONObjects and not an object itself. You should try this:
JSONObject json = new JSONObject(acc);
JSONArray jsonarr = json.getJSONArray("nameservice");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject nameservice = jsonarr.getJSONObject(i);
String id = nameservice.getString("id");
String name = nameservice.getString("name");
}
I don't understand why you do it manualy if you already have Spring Framework.
Take a look at MappingJackson2HttpMessageConverter and configure your ServletDispatcher accordingly. Spring will automatically convert your objects to JSON string and vice versa.
After that your controller method will be looked like:
#RequestMapping("/saveName")
#ResponseBody
public Object saveName(#RequestBody SomeObject obj) {
SomeObject newObj = doSomething(obj);
return newObj;
}
I have a JSON file which contains an array of item objects:
{
"item": [
{
"title": "TitleA",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
},
{
"title": "TitleB",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
}
]
}
Now I know how to get the "title", but I don't know how I would access the "-url" within "media:content" for example, since it seems to be a JSON object within the Item object. How would I get this value and assign it to a value in my Item class?
try as to get "-url" within "media:content" from current json string :
JSONObject jsonObject = new JSONObject("Your JSON STRING HERE");
JSONArray jsonArray =jsonObject.getJSONArray("item");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectitem=
jsonArray.getJSONObject(i);
// get title or link here
String strtitle=jsonObjectitem.getString("title");
//....get other values in same way
// get media:content json object
JSONObject jsonObjectmediacontent =
jsonObjectitem.getJSONObject("media:content");
// get url,medium,...
String strurl=jsonObjectmediacontent.getString("-url");
//....get other values in same way
}
Write below code to parse -url string, it will solve your problem.
JSONObject mMainJsonObj = new JSONObject("Pass Json Response String Here");
JSONArray mItemJsonArray = mMainJsonObj.getJSONArray("item");
for (int i = 0; i < mItemJsonArray.length(); i++) {
JSONObject mJsonObj1 = mItemJsonArray.getJSONObject(i);
String mTitle = mJsonObj1.getString("title");
String mLink = mJsonObj1.getString("link");
JSONObject mJsonObjGuid = mJsonObj1.getJSONObject("guid");
String mIsPermLink = mJsonObjGuid.getString("-isPermaLink");
String mText = mJsonObjGuid.getString("#text");
JSONObject mJsonObjAtomLink = mJsonObj1.getJSONObject("atom:link");
String mRel = mJsonObjAtomLink.getString("-rel");
String mHref = mJsonObjAtomLink.getString("-href");
JSONObject mJsonObjMediaContent = mJsonObj1.getJSONObject("media:content");
String mUrl = mJsonObjMediaContent.getString("-url");
String mMedium = mJsonObjMediaContent.getString("-medium");
String mHeight = mJsonObjMediaContent.getString("-height");
String mWidth = mJsonObjMediaContent.getString("-width");
}
And see below link for more information.
Json Parsing Example
Solution with Jackson: read your JSON into a JsonNode using an ObjectMapper and retrieve your values like this:
// Since JsonNode implements Iterable of itself and cycles through array elements,
// this works
for (final JsonNode element: node)
doSomethingWith(element.get("media:content").get("-url"));
I have the following JSON:
{
"registration": {
"name": "Vik Kumar",
"first_name": "Vik",
"last_name": "Kumar",
"bloodGroup": "B-",
"gender": "male",
"birthday": "10\/31\/1983",
"email": "vik.ceo\u0040gmail.com",
"cellPhone": "1234123456",
"homePhone": "1234123457",
"officePhone": "1234123458",
"primaryAddress": "jdfjfgj",
"area": "jfdjdfj",
"location": {
"name": "Redwood Shores, California",
"id": 103107903062719
},
"subscribe": true,
"eyePledge": false,
"reference": "fgfgfgfg"
}
}
I am using the following code to parse it:
JsonNode json = new ObjectMapper().readTree(jsonString);
JsonNode registration_fields = json.get("registration");
Iterator<String> fieldNames = registration_fields.getFieldNames();
while(fieldNames.hasNext()){
String fieldName = fieldNames.next();
String fieldValue = registration_fields.get(fieldName).asText();
System.out.println(fieldName+" : "+fieldValue);
}
This works fine and it print all the values except for location which is kind of another level of nesting. I tried the same trick as above code to pass json.get("location") but that does not work. Please suggest how to make it work for location.
You need to detect when you are dealing with a (nested) Object using JsonNode#isObject:
public static void printAll(JsonNode node) {
Iterator<String> fieldNames = node.getFieldNames();
while(fieldNames.hasNext()){
String fieldName = fieldNames.next();
JsonNode fieldValue = node.get(fieldName);
if (fieldValue.isObject()) {
System.out.println(fieldName + " :");
printAll(fieldValue);
} else {
String value = fieldValue.asText();
System.out.println(fieldName + " : " + value);
}
}
}
Thus, when you reach an object, such as location, you'll call the printAll recursively to print all its inner values.
org.codehaus.jackson.JsonNode json = new ObjectMapper().readTree(jsonString);
org.codehaus.jackson.JsonNode registration_fields = json.get("registration");
printAll(registration_fields);
Since location is nested within registration, you need to use:
registration_fields.get("location");
to get it. But isn't it already processed by the while-loop, why do you need to get it separately?