Related
Sorry, possible newbie question, I'm trying to learn Java while contributing to a project at work. Actually code is Groovy (& we're using Grails) but assume that's the same for this purpose.
I'm trying to convert a JDBC ResultSet to JSON (to send to the front end). Got the following code from a blog:
// Convert JDBC ResultSet to JSON string
public static JSONArray convertToJSON(ResultSet resultSet)
throws Exception {
JSONArray jsonArray = new JSONArray();
ResultSetMetaData metaData = resultSet.getMetaData(); // Result set meta data
int total_columns = metaData.getColumnCount(); // Number of columns in the row
while (resultSet.next()) { // Take each row from the result set
JSONObject obj = new JSONObject();
for (int i = 0; i < total_columns; i++) {
obj.put(metaData.getColumnLabel(i + 1)
.toLowerCase(), resultSet.getObject(i + 1));
}
jsonArray.put(obj);
}
return jsonArray.toString(); // Return as JSON string
}
This (I believe) will give me a JSON structure with the data in the root/top of the JSON. I want to move it into a sub-field (called e.g. 'data') and then have another couple of key/value pairs at root level. How would I modify the code to do this please? (I could pass the couple of extra values in as params)
Thanks.
You can do something like
JSONObject rootObject = new JsonObject();
rootObject.put("data", jsonArray);
This will let you treat your JSON like a key-value pair and should accomplish what you are asking.
Additionally, you may want to look at using an ObjectMapper to convert your object to JSON. This would allow you to create a JSONObject from a Java object with something like objectMapper.writeValueAsString(resultSet)
I think there is an error in the code snippet you provided, since your signature states JSONArray as a return type but you return a String, anyway here is what I would suggest:
public static JSONObject convertToJSON(ResultSet resultSet)
throws Exception {
JSONObject root = new JSONObject();
JSONArray jsonArray = new JSONArray();
root.put("data", jsonArray);
ResultSetMetaData metaData = resultSet.getMetaData(); // Result set meta data
int total_columns = metaData.getColumnCount(); // Number of columns in the row
while (resultSet.next()) { // Take each row from the result set
JSONObject obj = new JSONObject();
for (int i = 0; i < total_columns; i++) {
obj.put(metaData.getColumnLabel(i + 1)
.toLowerCase(), resultSet.getObject(i + 1));
}
jsonArray.put(obj);
}
return root;
}
As this is a Groovy question, you could make your code more Groovy ;-)
static String convertToJSON(ResultSet resultSet) throws Exception {
def metaData = resultSet.metaData // Result set meta data
def result = []
while (resultSet.next()) { // Take each row from the result set
result << (1..metaData.columnCount).collectEntries {
[metaData.getColumnLabel(it).toLowerCase(), resultSet.getObject(it)]
}
}
return new JsonBuilder(result).toString() // Return as JSON string
}
I am trying retrieving the following JSON data from imagga's image recognition API.
{"results":[{"image":"http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg","tagging_id":null,"tags":[{"confidence":63.346307851163395,"tag":"valley"},{"confidence":60.66263009377379,"tag":"mountain"},{"confidence":44.39096006516168,"tag":"canyon"},{"confidence":42.08210930346856,"tag":"landscape"},{"confidence":33.52198895357515,"tag":"geological formation"},{"confidence":32.702112467737216,"tag":"mountains"},{"confidence":28.626223994488203,"tag":"glacier"},{"confidence":28.36,"tag":"natural depression"},{"confidence":28.03481906795487,"tag":"ravine"},{"confidence":27.269738461024804,"tag":"sky"},{"confidence":26.130797131953397,"tag":"rock"},{"confidence":23.11898739400327,"tag":"travel"},{"confidence":21.75182989551758,"tag":"alp"},{"confidence":20.956625061326214,"tag":"national"},{"confidence":20.15360199670358,"tag":"park"},{"confidence":19.826365024393702,"tag":"stone"},{"confidence":19.717420656127437,"tag":"water"},{"confidence":18.049071926896588,"tag":"river"},{"confidence":17.81629840041474,"tag":"hill"},{"confidence":17.30594970410163,"tag":"tourism"},{"confidence":17.192663177192692,"tag":"clouds"},{"confidence":16.53588724897844,"tag":"scenic"},{"confidence":15.98967256769248,"tag":"peak"},{"confidence":15.792599629554461,"tag":"lake"},{"confidence":15.532788988165363,"tag":"scenery"},{"confidence":15.453814687301834,"tag":"snow"},{"confidence":15.232632664896412,"tag":"outdoors"},{"confidence":15.212304004139495,"tag":"range"},{"confidence":15.042325772263556,"tag":"hiking"},{"confidence":14.958759294889424,"tag":"tree"},{"confidence":14.78842712696222,"tag":"forest"},{"confidence":12.853490785491731,"tag":"grass"},{"confidence":12.242518977753525,"tag":"desert"},{"confidence":12.095999999999998,"tag":"natural elevation"},{"confidence":12.03899501602295,"tag":"america"},{"confidence":11.49381779097963,"tag":"environment"},{"confidence":11.250534926394025,"tag":"usa"},{"confidence":10.935999552280517,"tag":"panorama"},{"confidence":10.838870815021957,"tag":"trees"},{"confidence":10.77081532273937,"tag":"south"},{"confidence":10.385222667460749,"tag":"summer"},{"confidence":9.967993711501377,"tag":"cloud"},{"confidence":9.960797892906747,"tag":"wild"},{"confidence":9.840206836878211,"tag":"natural"},{"confidence":9.64736797817423,"tag":"geology"},{"confidence":9.622992778171428,"tag":"rocky"},{"confidence":9.5011692563878,"tag":"outdoor"},{"confidence":9.36921935993258,"tag":"wilderness"},{"confidence":9.360136841263397,"tag":"vacation"},{"confidence":9.295849004816608,"tag":"rocks"},{"confidence":9.200756690906687,"tag":"high"},{"confidence":9.098263071652019,"tag":"highland"},{"confidence":8.912795414022,"tag":"tourist"},{"confidence":8.871604649828521,"tag":"hike"},{"confidence":8.849249986309006,"tag":"landmark"},{"confidence":8.696713373486205,"tag":"cliff"},{"confidence":8.600291951670297,"tag":"scene"},{"confidence":8.535889495009538,"tag":"stream"},{"confidence":8.530021520404471,"tag":"sunny"},{"confidence":8.255077489679804,"tag":"altitude"},{"confidence":8.016191292928964,"tag":"trail"},{"confidence":7.9938748285500605,"tag":"autumn"},{"confidence":7.985278417869093,"tag":"california"},{"confidence":7.927492176055299,"tag":"spain"},{"confidence":7.774043777890904,"tag":"adventure"},{"confidence":7.560207874392119,"tag":"peaceful"},{"confidence":7.485827508554503,"tag":"fall"},{"confidence":7.283862421876644,"tag":"erosion"},{"confidence":7.272123549182718,"tag":"terrain"},{"confidence":7.24510515635207,"tag":"rural"},{"confidence":7.234934522337296,"tag":"vista"},{"confidence":7.092282542389207,"tag":"holiday"}]}]}
I am using http://www.java2s.com/Code/Jar/o/Downloadorgjson20130603jar.htm library.
My Java code is as follows:
String imageUrl = "http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg",
apiKey = "",
apiSecret = "";
// These code snippets use an open-source library. http://unirest.io/java
HttpResponse response = Unirest.get("https://api.imagga.com/v1/tagging")
.queryString("url", imageUrl)
.basicAuth(apiKey, apiSecret)
.header("Accept", "application/json")
.asJson();
String js = response.getBody().toString();
System.out.println(js.toString());
JSONObject jObject = new JSONObject(response.getBody()); // json
System.out.print("hello");
JSONObject data1 = jObject.getJSONObject("results"); // get data
System.out.print(data1); // object
String projectname = data1.getString("tags"); // get the name
// from data.
System.out.print(projectname);
I am getting the error that
Exception in thread "main" org.json.JSONException:
JSONObject["results"] not found.
What I want to get is the list of "tag" and "confidence".
try this
JSONArray data1 = jObject.getJSONArray("results");
Edited Answer
String js = response.getBody().toString();
System.out.println(js.toString());
JSONObject jObject = new JSONObject(js); // json
System.out.print("hello");
JSONArray data1 = jObject.getJSONArray("results");
for(int i = 0; i < data1.length; i++)
{
JSONObject jsonObject = data1.getJSONObject(i);
String projectn ame = jsonObject.getString("tagging_id");
System.out.print(projectname);
JSONArray tagArray = jsonObject.getJsonArray("tags");
for(int j = 0; j < tagArray.length; j++)
{
JSONObject tagObject = tagArray.getJSON(j);
System.out.println("Tag == " + tagObject.getString("tag"));
}
}
To make your life more easy I'd go to model the Objects as POJO's and let Jackson's Objectmapper do the magic.
See http://wiki.fasterxml.com/JacksonDataBinding
I suppose you should try jObject.getJSONArray("results") instead of jObject.getJSONObject("results").
There is also a good tool to convert json to java: http://json2java.azurewebsites.net/
If you use it, you will see:
...other code...
public class RootObject
{
private ArrayList<Result> results;
public ArrayList<Result> getResults() { return this.results; }
public void setResults(ArrayList<Result> results) { this.results = results; }
}
...other code...
And results is list here, so use getJSONArray instead of getJSONObject
If you look into your json results has an array in it and therefore you should use getJSONArray and not getJSONObject.
JSONArray data1 = jObject.getJSONArray("results");
This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 6 years ago.
I'm trying to convert a the following string so that I can get the properties out of it. I'm trying to insert these in the DB by getting their properties and then making objects out of them
[{"ParkingSpaces;;;;":"Name;CarPlate;Description;ExpirationDate;Owner"},{"ParkingSpaces;;;;":"A5;T555;Parkingspace A5;;"},{"ParkingSpaces;;;;":"A6;T666;Parkingspace A6;;"},{"ParkingSpaces;;;;":"A7;T777;Parkingspace A7;;"},{"ParkingSpaces;;;;":""}]
I got this string from a CSV file.
Anyone who has an idea on how I can approach this?
Thanks in advance.
Your code is quite messy, but it's doable. You can either use simple JSON parsing method like in the example:
final String json = "[{\"ParkingSpaces;;;;\":\"Name;CarPlate;Description;ExpirationDate;Owner\","
{\"ParkingSpaces;;;;\":\"A5;T555;Parkingspace A5;;\"},{\"ParkingSpaces;;;;\":\"A6;T666;Parkingspace A6;;\"},{\"ParkingSpaces;;;;\":\"A7;T777;Parkingspace A7;;\"},{\"ParkingSpaces;;;;\":\"\"}]";
final org.json.JSONArray jSONArray = new JSONArray(json);
for (int i = 0; i < jSONArray.length(); i++) {
final org.json.JSONObject jSONObject = jSONArray.getJSONObject(i);
final String parkingSpaces = jSONObject.getString("ParkingSpaces;;;;");
final String spaces[] = parkingSpaces.split(";");
System.out.println(Arrays.toString(spaces));
}
}
or use some bindings like Jackson.
What you have there is JSON with some semicolon separated strings in it. I wouldn't call this a CSV format at all.
You could parse the JSON to Java objects with a JSON parser like Gson, but you'll still need to pick the "columns" out of the Java object since they are not properly defined in JSON.
Something like this should work, I recommend you add more error checking than I have though:
public class DBEntry {
#SerializedName("ParkingSpaces;;;;")
#Expose
private String ParkingSpaces;
public String getParkingSpaces() {
return ParkingSpaces;
}
public void setParkingSpaces(String ParkingSpaces) {
this.ParkingSpaces = ParkingSpaces;
}
}
public static void main(String[] args) {
String json = "[{\"ParkingSpaces;;;;\":\"Name;CarPlate;Description;ExpirationDate;Owner\"},{\"ParkingSpaces;;;;\":\"A5;T555;Parkingspace A5;;\"},{\"ParkingSpaces;;;;\":\"A6;T666;Parkingspace A6;;\"},{\"ParkingSpaces;;;;\":\"A7;T777;Parkingspace A7;;\"},{\"ParkingSpaces;;;;\":\"\"}]";
// Convert JSON to java objects using the popular Gson library
Gson gson = new Gson();
Type collectionType = new TypeToken<ArrayList<DBEntry>>(){}.getType();
List<DBEntry> results = gson.fromJson(json, collectionType);
boolean header = true;
for (DBEntry result : results) {
// Ignore the header and empty rows
if (header || result.getParkingSpaces().isEmpty()) { header = false; continue; }
// Grab the columns from the parking spaces string
String[] columns = result.getParkingSpaces().split(";");
// TODO: Store this record in your database
System.out.println("New entry: " + StringUtils.join(columns, ", "));
}
}
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
I have JSON object as follows:
member = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
In Java I want to parse the above json object and store the values in an arraylist.
I am seeking some code through which I can achieve this.
I'm assuming you want to store the interestKeys in a list.
Using the org.json library:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}
public class JsonParsing {
public static Properties properties = null;
public static JSONObject jsonObject = null;
static {
properties = new Properties();
}
public static void main(String[] args) {
try {
JSONParser jsonParser = new JSONParser();
File file = new File("src/main/java/read.json");
Object object = jsonParser.parse(new FileReader(file));
jsonObject = (JSONObject) object;
parseJson(jsonObject);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void getArray(Object object2) throws ParseException {
JSONArray jsonArr = (JSONArray) object2;
for (int k = 0; k < jsonArr.size(); k++) {
if (jsonArr.get(k) instanceof JSONObject) {
parseJson((JSONObject) jsonArr.get(k));
} else {
System.out.println(jsonArr.get(k));
}
}
}
public static void parseJson(JSONObject jsonObject) throws ParseException {
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (jsonObject.get(obj) instanceof JSONArray) {
System.out.println(obj.toString());
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
parseJson((JSONObject) jsonObject.get(obj));
} else {
System.out.println(obj.toString() + "\t"
+ jsonObject.get(obj));
}
}
}
}}
Thank you so much to #Code in another answer. I can read any JSON file thanks to your code. Now, I'm trying to organize all the elements by levels, for could use them!
I was working with Android reading a JSON from an URL and the only I had to change was the lines
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
for
Iterator<?> iterator = jsonObject.keys();
I share my implementation, to help someone:
public void parseJson(JSONObject jsonObject) throws ParseException, JSONException {
Iterator<?> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String obj = iterator.next().toString();
if (jsonObject.get(obj) instanceof JSONArray) {
//Toast.makeText(MainActivity.this, "Objeto: JSONArray", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString());
TextView txtView = new TextView(this);
txtView.setText(obj.toString());
layoutIzq.addView(txtView);
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
//Toast.makeText(MainActivity.this, "Objeto: JSONObject", Toast.LENGTH_SHORT).show();
parseJson((JSONObject) jsonObject.get(obj));
} else {
//Toast.makeText(MainActivity.this, "Objeto: Value", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString() + "\t"+ jsonObject.get(obj));
TextView txtView = new TextView(this);
txtView.setText(obj.toString() + "\t"+ jsonObject.get(obj));
layoutIzq.addView(txtView);
}
}
}
}
1.) Create an arraylist of appropriate type, in this case i.e String
2.) Create a JSONObject while passing your string to JSONObject constructor as input
As JSONObject notation is represented by braces i.e {}
Where as JSONArray notation is represented by square brackets i.e []
3.) Retrieve JSONArray from JSONObject (created at 2nd step) using "interests" as index.
4.) Traverse JASONArray using loops upto the length of array provided by length() function
5.) Retrieve your JSONObjects from JSONArray using getJSONObject(index) function
6.) Fetch the data from JSONObject using index '"interestKey"'.
Note : JSON parsing uses the escape sequence for special nested characters if the json response (usually from other JSON response APIs) contains quotes (") like this
`"{"key":"value"}"`
should be like this
`"{\"key\":\"value\"}"`
so you can use JSONParser to achieve escaped sequence format for safety as
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(inputString);
Code :
JSONParser parser = new JSONParser();
String response = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
JSONObject jsonObj = (JSONObject) parser.parse(response);
or
JSONObject jsonObj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> interestList = new ArrayList<String>();
JSONArray jsonArray = jsonObj.getJSONArray("interests");
for(int i = 0 ; i < jsonArray.length() ; i++){
interestList.add(jsonArray.getJSONObject(i).optString("interestKey"));
}
Note : Sometime you may see some exceptions when the values are not available in appropriate type or is there is no mapping key so in those cases when you are not sure about the presence of value so use optString, optInt, optBoolean etc which will simply return the default value if it is not present and even try to convert value to int if it is of string type and vice-versa so Simply No null or NumberFormat exceptions at all in case of missing key or value
From docs
Get an optional string associated with a key. It returns the
defaultValue if there is no such key.
public String optString(String key, String defaultValue) {
String missingKeyValue = json_data.optString("status","N/A");
// note there is no such key as "status" in response
// will return "N/A" if no key found
or To get empty string i.e "" if no key found then simply use
String missingKeyValue = json_data.optString("status");
// will return "" if no key found where "" is an empty string
Further reference to study
How to convert String to JSONObject in Java
Convert one array list item into multiple Items
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
Performance
Ease of use (code is simple to write and legible) - that goes with features.
For mobile apps: dependency/jar size
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs.
For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
public class MyObj {
private List<Interest> interests;
static final class Interest {
private String interestKey;
}
private static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws IOException {
MyObj o = JACKSON.readValue("{\"interests\": [{\"interestKey\": \"Dogs\"}, {\"interestKey\": \"Cats\" }]}", MyObj.class);
}
}
Let me know if you have any questions.
I am using a JSONObject in order to remove a certin attribute I don't need in a JSON String:
JSONObject jsonObject = new JSONObject(jsonString);
jsonObject.remove("owner");
jsonString = jsonObject.toString();
It works ok however the problem is that the JSONObject is "an unordered collection of name/value pairs" and I want to maintain the original order the String had before it went through the JSONObject manipulation.
Any idea how to do this?
try this
JSONObject jsonObject = new JSONObject(jsonString) {
/**
* changes the value of JSONObject.map to a LinkedHashMap in order to maintain
* order of keys.
*/
#Override
public JSONObject put(String key, Object value) throws JSONException {
try {
Field map = JSONObject.class.getDeclaredField("map");
map.setAccessible(true);
Object mapValue = map.get(this);
if (!(mapValue instanceof LinkedHashMap)) {
map.set(this, new LinkedHashMap<>());
}
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
return super.put(key, value);
}
};
jsonObject.remove("owner");
jsonString=jsonObject.toString();
You can't.
That is why we call it an unordered collection of name/value pairs.
Why you would need to do this, I'm not sure. But if you want ordering, you'll have to use a json array.
I have faced the same problem recently and just transitioned all our tests (which expect JSON attributes to be in the same order) to another JSON library:
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.5</version>
</dependency>
Internally it uses a LinkedHashMap, which maintains the order of attributes. This library is functionally equivalent to the json.org library, so I don't see any reason why not use it instead, at least for tests.
You can go for the JsonObject provided by the com.google.gson it is nearly the same with the JSONObject by org.json but some different functions.
For converting String to Json object and also maintains the order you can use:
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(<Json String>, JsonObject.class);
For eg:-
String jsonString = "your json String";
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
It just maintains the order of the JsonObject from the String.
If you can edit the server repose then change it to array of JSON objects.
JSON:
[
{PropertyName:"Date of Issue:",PropertyValue:"3/21/2011"},
PropertyName:"Report No:",PropertyValue:"2131196186"},{PropertyName:"Weight:",PropertyValue:"1.00"},
{PropertyName:"Report Type:",PropertyValue:"DG"}
]
And I handled it with JSONArray in client side (Android):
String tempresult="[{PropertyName:"Date of Issue:",PropertyValue:"3/21/2011"},PropertyName:"Report No:",PropertyValue:"2131196186"},PropertyName:"Weight:",PropertyValue:"1.00"},{PropertyName:"Report Type:",PropertyValue:"DG"}]"
JSONArray array = new JSONArray(tempresult);
for (int i = 0; i < array.length(); i++)
{
String key = array.getJSONObject(i).getString("PropertyName");
String value = array.getJSONObject(i).getString("PropertyValue");
rtnObject.put(key.trim(),value.trim()); //rtnObject is LinkedHashMap but can be any other object which can keep order.
}
You can use Jsckson library in case to maintain the order of Json keys.
It internally uses LinkedHashMap ( ordered ).
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
The code to remove a field, the removed JsonToken could itself be read if required.
String jsonString = "{\"name\":\"abc\",\"address\":\"add\",\"data\":[\"some 1\",\"some 2\",\"some3 3\"],\"age\":12,\"position\":8810.21}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
System.out.println("In original order:"+node.toString());
JsonToken removedToken = ((ObjectNode) node).remove("address").asToken();
System.out.println("Aft removal order:"+node.toString());
ObjectNode implementation uses a LinkedHashMap, which maintains the insertion order:
public ObjectNode(JsonNodeFactory nc) {
super(nc);
_children = new LinkedHashMap<String, JsonNode>();
}
Go on JSONObject class
Change from HashMap() to LinkedHashMap()
/**
* Construct an empty JSONObject.
*/
public JSONObject() {
this.map = new LinkedHashMap();
}
The LinkedHashMap class extends the Hashmap class. This class uses a doubly linked list containing all the entries of the hashed table, in the order in which the keys were inserted in the table: this allows the keys to be "ordered".
This is not easy, the main idea is to use LinkedHashMap, either pass in to the constructor (JSONObject(Map map)), or modify bytecode to handle the String parameter (JSONObject(String source)), which is the main use case. I got a solution in oson:
public static JSONObject getJSONObject(String source) {
try {
int lineNumberToReplace = 157;
ClassPool classPool = ClassPool.getDefault();
CtClass ctClass = classPool.get("org.json.JSONObject");
if (ctClass.isFrozen() || ctClass.isModified()) {
if (source == null) {
return new JSONObject();
} else {
return new JSONObject(source);
}
}
ctClass.stopPruning(true);
CtConstructor declaredConstructor = ctClass.getDeclaredConstructor(new CtClass[] {});
CodeAttribute codeAttribute = declaredConstructor.getMethodInfo().getCodeAttribute();
LineNumberAttribute lineNumberAttribute = (LineNumberAttribute)codeAttribute.getAttribute(LineNumberAttribute.tag);
// Index in bytecode array where the instruction starts
int startPc = lineNumberAttribute.toStartPc(lineNumberToReplace);
// Index in the bytecode array where the following instruction starts
int endPc = lineNumberAttribute.toStartPc(lineNumberToReplace+1);
// Let's now get the bytecode array
byte[] code = codeAttribute.getCode();
for (int i = startPc; i < endPc; i++) {
// change byte to a no operation code
code[i] = CodeAttribute.NOP;
}
declaredConstructor.insertAt(lineNumberToReplace, true, "$0.map = new java.util.LinkedHashMap();");
ctClass.writeFile();
if (source == null) {
return (JSONObject) ctClass.toClass().getConstructor().newInstance();
} else {
return (JSONObject) ctClass.toClass().getConstructor(String.class).newInstance(source);
}
} catch (Exception e) {
//e.printStackTrace();
}
if (source == null) {
return new JSONObject();
} else {
return new JSONObject(source);
}
}
need to include jar file from using mvn
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
From Android 20, JSONObject preserves the order as it uses LinkedHashMap to store namevaluepairs. Android 19 and below uses HashMap to store namevaluepairs. So, Android 19 and below doesn't preserve the order. If you are using 20 or above, don't worry, JSONObject will preserve the order. Or else, use JSONArray instead.
In JDK 8 and above, We can do it by using nashorn engine, supported in JDK 8.
Java 8 support to use js engine to evaluate:
String content = ..json content...
String name = "test";
String result = (String) engine.eval("var json = JSON.stringify("+content+");"
+ "var jsResult = JSON.parse(json);"
+ "jsResult.name = \"" + name + "\";"
+ "jsResult.version = \"1.0\";"
+ "JSON.stringify( jsResult );"
);
I was able to do this with help of classpath overriding.
created package package org.json.simple which is same as in jar and class named as JSONObject.
Took existing code from jar and updated the class by extending LinkedHashmap instead of Hashmap
by doing these 2 steps it will maintain the order, because preference of picking `JSONObject will be higher to pick from the new package created in step 1 than the jar.
I accomplished it by doing a:
JSONObject(json).put(key, ObjectMapper().writeValueAsString(ObjectMapper().readValue(string, whatever::class)))
So essentially I deserialize a string to an ordered class, then I serialize it again. But then I also had to format that string afterwards to remove escapes.
.replace("\\\"", "\"").replace("\"{", "{").replace("}\"", "}")
You may also have to replace null items as well if you don't want nulls.