Jackson LIb JsonArray format - java

I'm using jackson lib to add json object into jsonarray then Stringify my jsonarray to save it into my a table as string
JsonObject obj = new JsonObject();
obj.put("id",1).put("data","test");
JsonArray arr = new JsonArray();
arr.add(obj);
arr.toString();
//out : [{"map":{"id":1,"data":"test"},"empty":false}]
//result wanted : [{"id":1,"data":"test"}]
So how can I get the last result without map and empty keys, and why it adds those keys in the first place ?

I made small changes to the code, i used the following maven dependency https://mvnrepository.com/artifact/org.json/json/20160810 and you are using org.json but not jackson.
JSONObject obj = new JSONObject();
try {
obj.put("id",1).put("data","test");
} catch (JSONException e1) {
e1.printStackTrace();
}
JSONArray arr = new JSONArray();
arr.put(obj);
System.out.println(arr.toString());
output: [{"data":"test","id":1}]

ok, finally I get it. So, the documentation for the jackson module clearly shows how serialization of a JsonObject should be done. It is not using toString():
Serialization (JsonElement -> String)
ObjectMapper mapper = new ObjectMapper();
om.registerModule(new VertxJsonModule());
String jsonObject = mapper.writeValueAsString(new JsonObject());
String jsonArray = mapper.writeValueAsString(new JsonArray());

Related

Inserting values into a json array at a specific position in java?

I am getting a json array as a string from one activity to the other using intent extras.How can I insert a value at a certain position in the json array in java.
This is the json array that I am using.
{"result":[{"itembarcode":"BRMS","weight":"10","gross_wt":"1","stone_amt":"0","stone_wt":"","rate":"32000","making":"100","qty":"1","net_rate":"32100.0","item_total":"32100.0","sum_total":"64600.0"},
{"itembarcode":"MSAA0015","weight":"10","gross_wt":"11","stone_amt":"100000","stone_wt":"","rate":"32000","making":"500","qty":"1","net_rate":"32500.0","item_total":"32500.0","sum_total":"64600.0"}]}
And I would like to insert a doc_no inside this array something like
{"result":[{"doc_no":"IN1001","itembarcode":"BRMS","weight":"10","gross_wt":"1","stone_amt":"0","stone_wt":"","rate":"32000","making":"100","qty":"1","net_rate":"32100.0","item_total":"32100.0","sum_total":"64600.0"},
{"doc_no":"IN1001","itembarcode":"MSAA0015","weight":"10","gross_wt":"11","stone_amt":"100000","stone_wt":"","rate":"32000","making":"500","qty":"1","net_rate":"32500.0","item_total":"32500.0","sum_total":"64600.0"}]}
I have tried something like this
try {
JSONArray jr = new JSONArray(json);
for (int j=0;j<tot_length; j++)
{
JSONObject jb = jr.getJSONObject(j);
String docnumber = "IN1001";
jb.put("doc_no",docnumber);
}
Log.d("NEW JSON",json);
} catch (JSONException e) {
e.printStackTrace();
}
But it did not work for me.
Any help or suggestion is appreciated.Thank you.
JSONObject has no support for manage ordering .. so you need to use library like GSON
i have done this using GSON ..
lets try
try {
JSONObject jsonObject = new JSONObject(yourJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for(int i=0;i<jsonArray.length();i++){
LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<>();
JSONObject innerJosonObject = new JSONObject(jsonArray.getString(i));
// you need to put all values from jsonObject to map for managing the order..
linkedHashMap.put("doc_no","Custom Value");
linkedHashMap.put("itembarcode",innerJosonObject.getString("itembarcode"));
linkedHashMap.put("weight",innerJosonObject.getString("weight"));
linkedHashMap.put("gross_wt", innerJosonObject.getString("gross_wt"));
//..................... rest of others......
linkedHashMap.put("sum_total",innerJosonObject.getString("sum_total"));
Gson gson = new Gson();
// convert linkedHashMap to json string and it will keep the insertion order..
String string = gson.toJson(linkedHashMap,LinkedHashMap.class);
jsonArray.put(i,string);
}
jsonObject.put("result",jsonArray);
Log.e("json",jsonObject.toString());
// this prints jsonArray only [............]
Log.e("json_array", jsonArray.toString());
}catch (Exception e){
}
Output:`{"result":["{\"doc_no\":\"Custom Value\",\"itembarcode\":\"BRMS\",\"weight\":\"10\",\"gross_wt\":\"1\",\"sum_total\":\"64600.0\"}",
"{\"doc_no\":\"Custom Value\",\"itembarcode\":\"MSAA0015\",\"weight\":\"10\",\"gross_wt\":\"11\",\"sum_total\":\"64600.0\"}"]}`
Add this to gradle file
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.android.support:appcompat-v7:22.2.1'
}
Hope it helps .. Thank You
You need to store the changed jsonObject again in array
try this code
CODE
try {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject1 = new JSONObject(
"{ \r\n \"itembarcode\":\"BRMS\",\r\n \"weight\":\"10\",\r\n \"gross_wt\":\"1\",\r\n \"stone_amt\":\"0\",\r\n \"s\u200C\u200Btone_wt\":\"\",\r\n \"rate\":\"32000\",\r\n \"making\":\"100\",\r\n \"qty\":\"1\",\r\n \"net_rate\":\"32100.0\",\r\n \"item_to\u200C\u200Btal\":\"32100.0\",\r\n \"sum_total\":\"64600.0\"\r\n }");
JSONObject jsonObject2 = new JSONObject(
"{ \r\n \"itembarcode\":\"MSAA0015\",\r\n \"weight\":\"10\",\r\n \"gross_wt\":\"11\",\r\n \"stone_amt\":\"100000\",\r\n \"st\u200C\u200Bone_wt\":\"\",\r\n \"rate\":\"32000\",\r\n \"making\":\"500\",\r\n \"qty\":\"1\",\r\n \"net_rate\":\"32500.0\",\r\n \"item_tot\u200C\u200Bal\":\"32500.0\",\r\n \"sum_total\":\"64600.0\"\r\n }");
jsonArray.put(jsonObject1);
jsonArray.put(jsonObject2);
JSONObject finalObject = new JSONObject();
finalObject.put("result", jsonArray);
System.out.println("Old----->" + finalObject);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
json.put("doc_no", "IN1001");
jsonArray.put(i, json);
finalObject.put("result", jsonArray);
}
System.out.println("New----->" + finalObject);
} catch (Exception e) {
e.printStackTrace();
}
Output
Old----->{"result":[{"sum_total":"64600.0","making":"100","stone_amt":"0","rate":"32000","qty":"1","weight":"10","net_rate":"32100.0","gross_wt":"1","item_to\u200c\u200btal":"32100.0","s\u200c\u200btone_wt":"","itembarcode":"BRMS"},{"sum_total":"64600.0","making":"500","stone_amt":"100000","item_tot\u200c\u200bal":"32500.0","rate":"32000","qty":"1","st\u200c\u200bone_wt":"","weight":"10","net_rate":"32500.0","gross_wt":"11","itembarcode":"MSAA0015"}]}
New----->{"result":[{"sum_total":"64600.0","making":"100","stone_amt":"0","rate":"32000","qty":"1","doc_no":"IN1001","weight":"10","net_rate":"32100.0","gross_wt":"1","item_to\u200c\u200btal":"32100.0","s\u200c\u200btone_wt":"","itembarcode":"BRMS"},{"sum_total":"64600.0","making":"500","stone_amt":"100000","item_tot\u200c\u200bal":"32500.0","rate":"32000","qty":"1","doc_no":"IN1001","st\u200c\u200bone_wt":"","weight":"10","net_rate":"32500.0","gross_wt":"11","itembarcode":"MSAA0015"}]}
EDIT I didn't realise that there is one more jsonObject:)

SimpleJson: String to JSONArray

I get the following JSON:
[
{
"user_id": "someValue"
}
]
It's saved inside a String.
I would like to convert it to a JSONObject which fails (as the constructor assumes a JSON to start with {). As this doesn't seem to be possible I'd like to convert it to a JSONArray. How can I do that with SimpleJson?
JSONParser parser = new JSONParser();
JSONArray array = (JSONArray)parser.parse("[{\"user_id\": 1}]");
System.out.println(((JSONObject)array.get(0)).get("user_id"));
You need to cast to a JSONArray as that is what the string contains.
For your task you could use code as bellow:
String t = "[{\"user_id\": \"someValue\"}]";
JSONParser parser = new JSONParser();
JSONArray obj = (JSONArray) parser.parse(t);
System.out.println(obj.get(0));
And result would be JSONObject.
String actualJsonObject = // assuming that this variable contains actual object what ever u want to pass as per your question says
JSONParser parser = new JSONParser();
JSONArray userdataArray= (JSONArray) parser.parse(actualJsonObject );
if(userdataArray.size()>0){
for (Object user : userdataArray) {
JSONObject jsonrow=(JSONObject)parser.parse(String.valueOf(user));
String User_Id= (String)jsonrow.get("user_Id"); \\ Each User_Id will be displayed.
} else{
System.out.println("Empty Array....");
}
It works for me.
String jsonString = "[{\"user_id\": \"someValue\"}]";
JSONArray jsonArray = new JSONArray();
JSONParser parser = new JSONParser();
try {
jsonArray = (JSONArray) parser.parse(js);
} catch (ParseException e) {
e.printStackTrace();
}

How to create multi JSON object in java

I want to create a object array in JSONObjet. But not run in java. Please help me.
JSONObject jo[] = new JSONObject[10];
jo[0].put("A","a");
jo[1].put("B","b");
jo[2].put("B","c");
...
java
You are probably looking for this -
JSONObject jo[] = new JSONObject[10];
jo[0]=new JSONObject().put("A","a");
jo[1]=new JSONObject().put("B","b");
jo[2]=new JSONObject().put("B","c");
Use JSONArray instead of that like this -
public void getJSONArray() throws JSONException {
JSONArray jo= new JSONArray();
JSONObject obj1= new JSONObject();
obj1.put("A","a");
JSONObject obj2= new JSONObject();
obj2.put("B","b");
JSONObject obj3= new JSONObject();
obj3.put("B","c");
jo.put(obj1);
jo.put(obj2);
jo.put(obj3);
System.out.println(jo.toString());
}
Output -
[{"A":"a"},{"B":"b"},{"B":"c"}]

How to write a JSONObject to a file, which has JSONArray inside it, in Java?

I have JSON file, that I need to read, edit and write out again.
Reading works fine, I struggle with the write part of the JSON Array in my data.
I use JSON.simple library to work with JSON in Java.
The file looks like this:
{
"maxUsers":100,
"maxTextLength":2000,
"maxFileSize":2000,
"services":
[
{
"serviceName":"Яндекc",
"className":"YandexConnector.class",
"isEnabled":true
},
{
"serviceName":"Google",
"className":"GoogleConnector.class",
"isEnabled":false
}
]
}
When I try to write JSON-data (variable obj) to file, the services array is broken. My writing code:
JSONObject obj = new JSONObject();
obj.put("maxUsers", this.getMaxUsers());
obj.put("maxTextLength", this.getMaxTextLength());
obj.put("maxFileSize", this.getMaxFileSize());
JSONArray servicesJSON = new JSONArray();
ArrayList<Service> servicesArray = this.getServices();
for(int i=0; i< servicesArray.size(); i++)
{
servicesJSON.add(servicesArray.get(i));
}
obj.put("services", servicesJSON);
FileWriter file = new FileWriter(filename);
obj.writeJSONString(file);
file.flush();
file.close();
This outputs:
{
"services":
[
translator.settings.Service#121c5df,
translator.settings.Service#45f4ae
],
"maxTextLength":2000,
"maxUsers":100,
"maxFileSize":2000
}
How can I write the JSON data correctly to a file, if I have it in a JSONArray like services ?
The code, where I read the JSON data from the file (that works fine):
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filename));
JSONObject jsonObject = (JSONObject) obj;
setMaxUsers((Long) jsonObject.get("maxUsers"));
setMaxTextLength((Long) jsonObject.get("maxTextLength"));
setMaxFileSize((Long) jsonObject.get("maxFileSize"));
// get all list of services
JSONArray serv = (JSONArray) jsonObject.get("services");
for (int i = 0; i < serv.size(); i++) {
JSONObject service = (JSONObject) serv.get(i);
Service servec = new Service();
servec.setServiceName((String) service.get("serviceName"));
servec.setClassName((String) service.get("className"));
servec.setIsEnabled((Boolean) service.get("isEnabled"));
services.add(i, servec);
}
The editing part is not yet written, so I call the writing part directly after the reading.
Have a look at the examples of JSON-simple.
It says here that you need to put the Objects one by one into the Array, using only primitive and String values. You may use Collections like Map that by themselves only contain String or primitive values.
JSONArray list = new JSONArray();
list.add("foo");
list.add(new Integer(100));
list.add(new Double(1000.21));
list.add(new Boolean(true));
list.add(null);
StringWriter out = new StringWriter();
list.writeJSONString(out);
So, adding your Services is not allowed and won't work. You should add a toMap method in it where you convert it to a Map and fromMap to convert it back.
Like this (in Services.java):
public Map toMap() {
HashMap<String, String> serviceAsMap = new HashMap<>();
servicesAsMap.put("serviceName", serviceName);
servicesAsMap.put("className", this.class.getName() + ".class");
servicesAsMap.put("isEnabled", isEnabled);
// ... continue for all values
return servicesAsMap;
}
then you can use that Map to populate your JSONArray like this:
JSONArray servicesJSON = new JSONArray();
ArrayList<Service> servicesArray = this.getServices();
for(int i=0; i< servicesArray.size(); i++)
{
servicesJSON.add(servicesArray.get(i).toMap()); // use the toMap method here.
}
obj.put("services", servicesJSON);
Have a look at JSONArray Documentation.Here you will get list of methods available.This JSONArray is inherited from java.util.ArrayList,so we can use the methods available for ArrayList to JSONArray.
JSONArray userList = JSONFile.readJSONArray("users.json");
JSONArray newuserList = new JSONArray() ;
JSONObject jsonobject , newjsonObject;
for (int i = 0; i < userList.size(); i++) {
jsonobject = (JSONObject) userList.get(i);
String id = (String) jsonObject.get("id");
String pass = (String) jsonObject.get("password");
newuserList.add(jsonObject);
// Here we are putting json object into newuserList which is of JSONArray type
try{
FileWriter file = new FileWriter( "/users.json",false);
newuserList.writeJSONString(newuserList, file);
file.close();
}
catch(Exception e ){
e.getMessage();
}
Hope this will help !

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

I'm trying to parse below json file:
{"units":[{"id":42,
"title":"Hello World",
"position":1,
"v_id":9,
"sites":[[{"id":316,
"article":42,
"clip":133904
}],
{"length":5}]
}, ..]}
This is what I have tried:
Object obj = null;
JSONParser parser = new JSONParser();
Object unitsObj = parser.parse(new FileReader("file.json");
JSONObject unitsJson = (JSONObject) unitsObj;
JSONArray units = (JSONArray) unitsJson.get("units");
Iterator<String> unitsIterator = units.iterator();
while(unitsIterator.hasNext()){
Object uJson = unitsIterator.next();
JSONObject uj = (JSONObject) uJson;
obj = parser.parse(uj.get("sites").toString());
JSONArray jsonSites = (JSONArray) obj;
for(int i=0;i<jsonSites.size();i++){
JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.
System.out.println(site.get("article");
}
}
The code is not working when I try to parse the inner json array, so I get:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
The exception is pointing to this line:
JSONObject site = (JSONObject)jsonSites.get(i);
Any help? tnx.
I've found a working code:
JSONParser parser = new JSONParser();
Object obj = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);
If you don't need the array (like the author), you can simply use
JSONParser parser = new JSONParser();
Object obj = parser.parse(content);
The first element of the sites array is an array, as you can see indenting the JSON:
{"units":[{"id":42,
...
"sites":
[
[
{
"id":316,
"article":42,
"clip":133904
}
],
{"length":5}
]
...
}
Therefore you need to treat its value accordingly; probably you could do something like:
JSONObject site = (JSONObject)(((JSONArray)jsonSites.get(i)).get(0));
this worked:
System.out.println("resultList.toString() " + resultList);
org.json.JSONObject obj = new JSONObject(resultList);
org.json.JSONArray jsonArray = obj.getJSONArray(someField);
for(int i=0;i<jsonArray.length();i++){
System.out.println("array is " + jsonArray.get(i));
}
JSONObject site=jsonSites.getJSONObject(i) should work out
JSONObject obj=(JSONObject)JSONValue.parse(content);
JSONArray arr=(JSONArray)obj.get("units");
System.out.println(arr.get(1)); //this will print {"id":42,...sities ..}
#cyberz is right but explain it reverse
You can first read the whole content of file into a String.
FileInputStream fileInputStream = null;
String data="";
StringBuffer stringBuffer = new StringBuffer("");
try{
fileInputStream=new FileInputStream(filename);
int i;
while((i=fileInputStream.read())!=-1)
{
stringBuffer.append((char)i);
}
data = stringBuffer.toString();
}
catch(Exception e){
LoggerUtil.printStackTrace(e);
}
finally{
if(fileInputStream!=null){
fileInputStream.close();
}
}
Now You will have the whole content into String ( data variable ).
JSONParser parser = new JSONParser();
org.json.simple.JSONArray jsonArray= (org.json.simple.JSONArray) parser.parse(data);
After that you can use jsonArray as you want.
If you want to re-filter the json data you can use following method. Given example is getting all document data from couchdb.
{
Gson gson = new Gson();
String resultJson = restTemplate.getForObject(url+"_all_docs?include_docs=true", String.class);
JSONObject object = (JSONObject) new JSONParser().parse(resultJson);
JSONArray rowdata = (JSONArray) object.get("rows");
List<Object>list=new ArrayList<Object>();
for(int i=0;i<rowdata.size();i++) {
JSONObject index = (JSONObject) rowdata.get(i);
JSONObject data = (JSONObject) index.get("doc");
list.add(data);
}
// convert your list to json
String devicelist = gson.toJson(list);
return devicelist;
}
JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.
The return type of jsonSites.get(i) is JSONArray not JSONObject.
Because sites have two '[', two means there are two arrays here.
use your jsonsimpleobject direclty like below
JSONObject unitsObj = parser.parse(new FileReader("file.json");
JSONObject baseReq
LinkedHashMap insert = (LinkedHashMap) baseReq.get("insert");
LinkedHashMap delete = (LinkedHashMap) baseReq.get("delete");

Categories