Inserting values into a json array at a specific position in java? - 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:)

Related

How to post this type of data in JSON Object

I have to post this type of data into Json. I don't want to convert cat in string. I only want single quote of item enclosing with double quote.
{"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}
My Json
JSONObject jsonobject1 = new JSONObject();
jsonobject.put("p02bvsd", "cal_dis");
jsonobject.put("ovpsc7s", jsonobject1);
jsonobject1.put("cat", hCategory);
Here hCategory is Hashset.
I want to json like this
{"p02bvsd":"cal_dis","ovpsc7s":{"cat": ["'Furniture'", "'Bikes'", "'Others'" ]}}
JSONObject jsonobject = new JSONObject();
jsonobject.put("p02bvsd", "cal_dis");
JSONObject jsonobject1 = new JSONObject();
List <String> list = new ArrayList <String>();
list.add("Furniture");
list.add("Bikes");
list.add("Others");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
try {
jsonobject1.put("cat", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonobject.put("ovpsc7s", jsonobject1);
String myString = "{\"p02bvsd\":\"cal_dis\",\"ovpsc7s\":{\"cat\":[\"\'Furniture\'\", \"\'Bikes\'\", \"\'Others\'\"]}}";
JSONObject wholeThing = new JSONObject(myString); // contains {"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}
JSONObject jsonp02bvsd = wholeThing.getJSONObject("p02bvsd"); // contains {"p02bvsd":"cal_dis"}
JSONObject jsonovpsc7s = wholeThing.getJSONObject("ovpsc7s"); // contains {"ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}
JSONArray jsonCatArray = jsonp02bvsd.getJSONArray("cat"); // contains ["'Furniture'", "'Bikes'", "'Others'"]
String first = jsonCatArray.getString(0); // contains 'Furniture'

Convert Json String to List in Android

strResponse = {"GetCitiesResult":["1-Vizag","2-Hyderbad","3-Pune","4-Chennai","9-123","11-Rohatash","12-gopi","13-Rohatash","14-Rohatash","10-123"]}
JSONObject json = new JSONObject(strResponse);
// get LL json object
String json_LL = json.getJSONObject("GetCitiesResult").toString();
Now i want to convert the json string to List in andriod
Please make sure your response String is correct format, if it is, then try this:
try {
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject(strResponse);
JSONArray array = json.getJSONArray("GetCitiesResult");
for (int i = 0; i < array.length(); i++) {
list.add(array.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
Simply using Gson library you can convert json response to pojo class.
Copy the json string to create pojo structure using this link: http://www.jsonschema2pojo.org/
Gson gson = new Gson();
GetCitiesResult citiesResult = gson.fromJson(responseString, GetCitiesResult.class);
It will give the GetCitiesResult object inside that object you get a list of your response like
public List<String> getGetCitiesResult() {
return getCitiesResult;
}
Call only citiesResult.getGetCitiesResult(); it will give a list of cities.
You can also use this library com.squareup.retrofit2:converter-gson:2.1.0
This piece of code did the trick
List<String> list3 = json.getJSONArray("GetCitiesResult").toList()
.stream()
.map(o -> (String) o)
.collect(Collectors.toList());
list3.forEach(System.out::println);
And printed:
1-Vizag
2-Hyderbad
3-Pune
4-Chennai
9-123
11-Rohatash
12-gopi
13-Rohatash
14-Rohatash
10-123
below is code:
private void parse(String response) {
try {
List<String> stringList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("GetCitiesResult");
for (int i=0; i <jsonArray.length(); i++){
stringList.add(jsonArray.getString(i));
}
Log.d ("asd", "--------"+ stringList);
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it will help.
Output is when print list :
--------[1-Vizag, 2-Hyderbad, 3-Pune, 4-Chennai, 9-123, 11-Rohatash, 12-gopi, 13-Rohatash, 14-Rohatash, 10-123]
Ok you must know first something about JSON
Json object is be {// some attribute}
Json Array is be [// some attribute]
Now You have
{"GetCitiesResult":["1-Vizag","2-Hyderbad",
"3-Pune","4-Chennai","9-123","11-Rohatash",
"12-gopi","13-Rohatash","14-Rohatash","10-123"]}
That`s Means you have JSON array is GetCitiesResult
which have array of String
Now Try this
JSONObject obj = new JSONObject(data);
JSONArray loadeddata = new JSONArray(obj.getString("GetCitiesResult"));
for (int i = 0; i <DoctorData.length(); i++) {// what to do here}
where data is your String

How to get values from JSONObject in Java?

I am trying to parse a JsonArray and get its values but I am gettign error when I use
jitem.getString("firstitem");
or
jitem.getJSONObject("firstitem");
or
jitem.get("firstitem");
Following is the code snippet.
JSONArray arr_items = new JSONArray(str);
if(arr_items!=null && arr_items.size()>0){
for(int i=0;i<arr_items.size();i++){
JSONObject jitem = arr_items.getJSONObject(i);//works fine till here
jitem.getString("firstitem"); //throws exception here
}
This is the JSONArray that I am parsing
[{"firstitem":"dgfd","secondtitem":"dfgfdgfdg","thirditem":"fdgfdgdf#sjhasjkdsha.com","fourthitem":"jkksdjklsfjskj"}]
what I am doing wrong? How to get these values by using keys?
Update:Note This array and its parameters are not null at all. They all have valid values.
First check arr_items is not empty.
Then, try surrounding your snippet with try/catch :
try {
your snippet
} catch (JSONException e) {
e.printStackTrace();
}
Check below
String json ="{'array':" + "[{'firstitem':'dgfd','secondtitem':'dfgfdgfdg','thirditem':'fdgfdgdf#sjhasjkdsha.com','fourthitem':'jkksdjklsfjskj'}]"+ "}";
JSONObject myjson = new JSONObject(json);
JSONArray the_json_array = myjson.getJSONArray("array");
int size = the_json_array.length();
// ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
// arrays.add(another_json_object);
System.out.println(another_json_object.get("firstitem"));
}
it require some array name so appended array name to it , if you want without it you have to add GSON.

Jackson LIb JsonArray format

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());

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 !

Categories