Convert JSON String to JSON Array - java

Hello i call a service if it contains multiple objects it make list but when it contain only one object it return a single object not a list [] are missing , actually i want to convert them into java class using gson but in case of single exception it throw exception but when it contain list it work fine i actually need to convert my single gSON string to array ,please help me ..here is the string
{
"response":{
"projects":{
"project":{
"ixWorkflow":1,
"sEmail":"j.a#loxvo.com",
"sPhone":"",
"ixProject":2,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"Project Default",
"fInbox":true,
"sPersonOwner":"junaid"
}
}
}
}
i want it to be like same as
{
"response":{
"projects":{
"project":[
{
"ixWorkflow":1,
"sEmail":"j.a#loxvo.com",
"sPhone":"",
"ixProject":6,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"project 2",
"fInbox":false,
"sPersonOwner":"junaid"
},
{
"ixWorkflow":1,
"sEmail":"j.a#loxvo.com",
"sPhone":"",
"ixProject":2,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"Project Default",
"fInbox":true,
"sPersonOwner":"junaid"
}
]
}
}
}

With reference to https://stackoverflow.com/a/7284813/1105291
Please try below code before you pass json to Gson for object conversion, and please let me know if you get any error. Only posibility that I can see is exception at if.
JSONObject jsonObject = new JSONObject(responseString);
JSONObject projectsJsonObject = jsonObject.getJSONObject("response").getJSONObject("projects");
if(projectsJsonObject.getJSONArray("project") == null)
{
JSONArray jsonArray = new JSONArray();
jsonArray.put(projectsJsonObject.getJSONObject("project"));
projectsJsonObject.put("project", jsonArray);
}
//Pass jsonObject to Gson

Use Google Gson
JsonParser parser = new JsonParser();
JsonObject o = (JsonObject)parser.parse("{\"a\": \"A\"}");

Related

Trouble in converting JSON object to JSON Array

I am currently using the Json-simple jar file and need to convert my json object into json array, I read on many places to use:
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject) parse.parse(jsonString);
JSONArray arr = jsonObject.getJSONArray("users");
However the getJSONArray() method isn't being recognized. It says cannot find symbol. I have imported all of the org.json package but not sure how this works.
My JSON is coming from a url and is:
{
"warnings":[
],
"users":[
{
"id":12345678,
"username":"abc123",
"firstname":"ABC",
"lastname":"DEF",
"fullname":"ABC",
"email":"abc#gmail.com",
"department":"Autoz",
"idnumber":"1234",
"firstaccess":2552,
"lastaccess":4242,
"auth":"ldap",
"suspended":false,
"confirmed":true,
"lang":"en",
"theme":"",
"timezone":"99",
"mailformat":1,
"description":"Software Engineer",
"descriptionformat":1,
"city":"Lahore",
"profileimageurlsmall":"srwegwegdrz",
"profileimageurl":"rbdrrebhez"
}
]
}

Remove nested key from a json object using java

I have the following json structure
{
"MerchHierarchyEBM":{
"DataArea":{
"Division":{
"UpdatedBy":"SN",
"Group":{
"GroupName":"Womens Fashion*",
"UpdatedBy":"Data Migration",
"UpdatedOn":"22-NOV-17",
"GroupID":"200"
},
"DivisionName":"Fashion",
"UpdatedOn":"22-NOV-17",
"DivisionID":"2000"
}
}
}
}
and i want to remove the "Group" key and value from the json object using java
i tried few things but didn't work following is my code .
JSONObject jsonObjIncomingDatanew =new JSONObject(Result);
jsonObjIncomingDatanew.remove("MerchHierarchyEBM.DataArea.Division.Group");
Try this:
JSONObject jsonObject = new JSONObject(Result);
jsonObject
.getJSONObject("MerchHierarchyEBM")
.getJSONObject("DataArea")
.getJSONObject("Division")
.remove("Group");
Or if getJSONObject() doesn't work, replace it with getAsJsonObject().

Parse.com add JSON Object to JSON Array

My problem is simple, I'd like to add a JSONObject to a JSONArray that I store in a MongoDB database. I can easily add all types of data like Strings, Ints etc but not JSONObjects.
I do this in my code :
public void done(ParseObject lan, ParseException e) {
if(e==null){
JSONObject object = new JSONObject();
try{
object.put("PlayerName","John");
object.put("ID",514145);
lan.add("Participants",object); //nothing gets inserted
lan.add("Participants",15); //works fine
lan.add("Participants",JSONObject.null); //works fine too
}catch (JSONException error){
}
lan.increment("Number");
lan.saveInBackground();
}else{
Log.i("Parse Error","error");
}
}
But nothing appears in my db and there's no error thrown.
Do you guys have any clue on how to do that ?
Try using object.toString() instead of object.
lan.add("Participants", object.toString());
JSON:
{"Participants":["{\"PlayerName\":\"John\",\"ID\":514145}"]}
To parse this JSON try this:
JSONObject jsonObj = new JSONObject(YOUR_JSON_STRING);
// Participants
JSONArray participantsJsonArray = jsonObj.getJSONArray("Participants");
// Participant
JSONObject participanJsonObject = participantsJsonArray.getJSONObject(0);
// PlayerName
String playerName = participanJsonObject.getString("PlayerName");
// ID
String id = participanJsonObject.getInt("ID");
Hope this will help~
Convert that Json Object into String and store it in string format
lan.add("Participants",object.toString());
And when you want to use that you can easily convert it into Json Object again like this
JSONObject jObj=new JSONObject("Your Json String");

Parsing a JSON file in Java using json-simple

I have created a .json file:
{
"numbers": [
{
"natural": "10",
"integer": "-1",
"real": "3.14159265",
"complex": {
"real": 10,
"imaginary": 2
},
"EOF": "yes"
}
]
}
and I want to parse it using Json Simple, in order to extract the content of the "natural" and the "imaginary".
This is what I have written so far:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); //the location of the file
JSONObject jsonObject = (JSONObject) obj;
String natural = (String) jsonObject.get("natural");
System.out.println(natural);
The problem is that the value of natural is "null" and not "10". Same thing happens when I write jsonObject.get("imaginary").
I have looked at many websites (including StackOverflow), I have followed the same way most people have written, but I am unable to fix this problem.
You need to find the JSONObject in the array first. You are trying to find the field natural of the top-level JSONObject, which only contains the field numbers so it is returning null because it can't find natural.
To fix this you must first get the numbers array.
Try this instead:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); //the location of the file
JSONObject jsonObject = (JSONObject) obj;
JSONArray numbers = (JSONArray) jsonObject.get("numbers");
for (Object number : numbers) {
JSONObject jsonNumber = (JSONObject) number;
String natural = (String) jsonNumber.get("natural");
System.out.println(natural);
}
The object in your file has exactly one property, named numbers.
There is no natural property.
You probably want to examine the objects inside that array.
Adding on to #Jermey Hanion's answer and comment, here is what I did to get "imaginary" and "natural"
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); //the location of the file
JSONObject jsonObject = (JSONObject) obj;
JSONArray numbers = (JSONArray) jsonObject.get("numbers");
for (Object number : numbers) {
JSONObject jsonNumber = (JSONObject) number;
String natural = (String) jsonNumber.get("natural");
JSONObject complex = (JSONObject) jsonNumber.get("complex");
String imaginary = (String) complex.get("imaginary");
System.out.println(natural);
}
Jeremey's answer for getting imaginary is not correct, or maybe it was correct. The above snippet is to my knowledge working on my project.
PS. Sorry for reviving the thread but I thought it would be a useful resource for people looking to learn JSON.simple

How to modify the JSON data and return the updated JSON data

We have a requirement to update the JSON data in middle and need to return the updated JSON data using java. Also it should support any type of JSON data.
ex:
Assume {object:{"color":"red","shape":"Triangle"}} is the JSON data and in this we need to update the shape value to Rectangle and we need to return the updated JSON data as below:
{object:{"color":"red","shape":"Rectangle"}}
For this we need to pass the element path ( which element we need to update) and updateText and JSON Data to the JAVA code.
here is the methodCall:
updateValue("object/shape", "Rectangle", "{object:{"color":"red","shape":"Triangle"}}")
We tried below code using Gson library. But with this code we are able to update the targeted Json element, but the requirement is to return the entire JSON data with the updated value.
So please suggest how do we re-build the JSON data with the updated text.
Below is the code we tried to update the Json Data.
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
String result = "";
for(String key : keys)
{
if (jsonObject.get(key) instanceof JsonObject)
{
jsonObject = (JsonObject)jsonObject.get(key);
}
else if(jsonObject.get(key) instanceof JsonArray)
{
JsonArray jsonArray = (JsonArray)jsonObject.get(key);
result = jsonArray.toString();
}
else
{
result = jsonObject.get(key).toString();
}
}
result = result.replace(result, updateText);
return result;
}
The problem lies in the way you do the replacements. When you translate the JsonObject to String, you lose the object, and after replacement, you just have the replaced String. To fix it, you need to operate directly on the object, instead of the String counterpart. Because JsonObject is mutable, holding a reference to the input will reflect the changes. One drawback is you can't replace a value in a JsonArray this way, partly because you don't know which element to replace. To accomplish that, you will need a little more in the input(either the value to replace or the element position).
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
JsonObject returnVal = jsonObject; // This holds the ref to target json object
JsonPrimitive jp = new JsonPrimitive(updateText);
String finalKey = keys[keys.length - 1];
for(String key : keys)
{
if (jsonObject.get(key).isJsonObject())
{
jsonObject = (JsonObject)jsonObject.get(key);
}
}
jsonObject.remove(finalKey);
jsonObject.add(finalKey, jp);
return returnVal.toString();
}
You can use JsonPath lib for that and try using the following code.
private static final Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
JsonNode updatedJson = JsonPath.using(configuration).parse(originaljson)
.set("use the path to go for value", "new value").json();
json = updatedJson.toString();

Categories