Json conversion - java

i want to create a Json like this
[{"sID":"221","mID":"0"},
{"sID":"222","mID":"11"},
{"sID":"223","mID":"11"}]
i have tried below code but that create Json just only for one line
JSONObject json = new JSONObject();
JSONObject manJson = new JSONObject();
manJson.put("sID", "23");
manJson.put("mID", "111");
json.put("",manJson);
this above code create Json like this
{"":{"sID":"23","mID":"111"}}
Please let me know about the changes required in that Java code thanks.

Change your code as:
JSONArray jsonArray = new JSONArray();
//Add 1st JSONObject to JSONArray
JSONObject jsonObjone = new JSONObject();
jsonObjone.put("sID", "221");
jsonObjone.put("mID","0");
jsonArray.put(jsonObjone.toString();
//Add 2nd JSONObject to JSONArray
JSONObject jsonObjtwo = new JSONObject();
jsonObjtwo.put("sID", "222");
jsonObjtwo.put("mID","11");
jsonArray.put(jsonObjtwo.toString());
//Add 3rd JSONObject to JSONArray
JSONObject jsonObjthrd = new JSONObject();
jsonObjthrd.put("sID", "223");
jsonObjthrd.put("mID","11");
jsonArray.put(jsonObjthrd.toString());

Use toJSONArray() method on manjson.

I recommend the jackson library it makes things very easy. To use it you would have an object like this...
class Ids {
private int Sid;
private int Mid;
public setSid(int Sid) {
this.Sid = Sid;
}
public setMid(int Mid) {
this.Mid = Mid;
}
public getSid() {
return Sid;
}
public getMid() {
return Mid;
}
}
Then you can use the objectMapper from the library to go from an array that you have in memory to a json String like so
Ids[] idsArray = new Ids[2];
//add ids object to array
String jsonString = objectMapper.writeValueAsString(idsArray);
Of course doing it this way depends on how your ids are stored but for me it generally makes my code a lot cleaner and the Jackson Library is pretty good performance wise.

Related

How to sum up two json values in java android?

Can any one tell me, how to sum two JSON objects values? Say, for an example:
First JSON
{
"json_obj":20,
}
Second JSON
{
"json_obj":40,
}
Here what I wanted is, I'm trying to create one JSON as same as like the above one, but i need to sum up two values of the JSON object "json_obj" and finally need to show it as like the below JSON
Resultant JSON
{
"json_obj":60
}
How to achieve this?
Try this,
JSONObject jsonObject1 = new JSONObject(First_JSON);
JSONObject jsonObject2 = new JSONObject(Socond_JSON);
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("json_obj", jsonObject1.getInt("json_obj")+jsonObject2.getInt("json_obj"));
Try this:
public String getAddedValues(String firstJson, String secondJson, String key){
JSONObject first = new JSONObject(firstJson);
JSONObject second = new JSONObject(secondJson);
int value = first.getInt(key) + second.getInt(key);
JSONObject output = new JSONObject();
output.put(key, value);
return output.toString();
}
Invoke it passing your json Strings and the "json_obj" String as key.
The idea is that you forst need to convert the json string into a Java object. Then you do your calculations, and finally you create another JSONObject with the result. JSONObject.toString() returns the common String representation you would expect as output :-)
You can try something like that:
public class CalcObj {
public int json_obj;
}
public String sumTwoJsons(String json1, String json2) {
Gson _gson = new Gson();
CalcObj obj1 = _gson.fromJson(json1, CalcObj.class);
CalcObj obj2 = _gson.fromJson(json2, CalcObj.class);
CalcObj objSum = new CalcObj();
objSum.json_obj = obj1.json_obj + obj2.json_obj;
return _gson.toJson(objSum );
}

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

Convert a string which has JSON into list and then add that list into JSON back

Here, I have a String which has JSONObject inside it like this :
String a = "{"company_name":"ABC","company_address":"hgfh"}";
I added this JSONObject into String with this code :
JSONObject company_one1 = new JSONObject();
company_one1.put("company_name", cmpy_name.getText()
.toString().trim());
company_one1.put("company_address", cmpy_addrs.getText()
.toString().trim());
a = company_one1.toString();
But now I've only the String and I need to add the JSONObject of this String a into an ArrayList and then convert that ArrayList into JSON which should look like :
{"id":"5","data":[{"company_name":"ABC","company_address":"hgfh","image":["cmFodWxtaXNocmE="]}]}
I have tried lots of things to change format like this, but I'm not getting exact format. Sometimes it adds backslashes \ itself into JSON beacuse we can't create a JSON which is already a JSON.
Please give me a proper solution for it.
Thanks in advance.
try this,
JSONArray imageArray = new JSONArray();
imageArray.put("cmFodWxtaXNocmE=");
//* you can add more to the image array by using the put method
JSONObject company_one1 = new JSONObject();
company_one1.put("company_name", cmpy_name.getText()
.toString().trim());
company_one1.put("company_address", cmpy_addrs.getText()
.toString().trim());
//* add the image array
company_one1.put("image", imageArray);
//* create a JSONArray for company types,
JSONArray dataArray = new JSONArray();
dataArray.put(company_one1);
//* you can add more to the array here by using the put method
//* now put all in one main JSONObject
JSONObject mainObj = new JSONObect();
mainObj.put("id", "5");
mainObj.put("data", dataArray);
String finalJsonString = mainObj.toString();
I don't think you are handling with JSON in a right wary. Maybe you should do like this:
try {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("company_name", "company_name");
map1.put("company_address", "company_address");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("company_name", "company_name");
map2.put("company_address", "company_address");
Map<String, String> map3 = new HashMap<String, String>();
map3.put("company_name", "company_name");
map3.put("company_address", "company_address");
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(map1);
list.add(map2);
list.add(map3);
JSONArray jsonArray = new JSONArray(list);
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id", "5");
jsonObject1.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
Here is the link, if you wish to use GSON as library to serialize and de-serialize json data. Visit Tutorail Java Object to/from JSON and library Gson
Here is pseudo code.(so it could not be compiled maybe)
But Gson is pretty easy and useful.
class Company {
String name;
... // constructors, getter/setters...
}
class CompanyGroup {
int id;
List<Company> companies;
... // constructors, getter/setters...
}
String name = "ABC";
Company a = new Company(name);
int id = 5;
CompanyGroup g = new CompanyGroup(5);
g.companies.add(a);
String r = new Gson().toJson(g);
System.out.println(r);
// I/System.outīš• {"companies":[{"name":"ABC"}],"id":5}

How to parse a JSONArray of JSONObjects in JAVA?

I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling

Json Array not properly generated

I have written java code for generating json of my searched data from file.But its not generating exact JsonArray. Its like
[{"item":"1617"},{"item":"1617"}]
instead of
[{"item":"747"},{"item":"1617"}].
Here 1617 is last item which is fetched from file.
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID);
if(j == userId) {
itemid = products.get("item");
jo.put("item",itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
you are actually creating one jSONobject object to handle two objects, shouldn't you need to create JSONObjects in the while loop? something like this, so every iteration in while loop will create a new JSONObject and add it to JSONArray
JSONArray ja = new JSONArray();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID, 10);
if(j == userId)
{
JSONObject jo = new JSONObject();
itemid = products.get("item");
jo.put("item", itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
Extra:
i am not sure how java does conversion for string to integer, but i think you should always specify radix when using parseInt so the strings like '09' will not be treated as octal value and converted to wrong value (atleast this is true in javascript :))
Integer.parseInt(productID, 10);
You must re-instantiate your JSonObject inside the loop because when you modify it you modify the underlying object which is referenced several times by your array. Move your JSONObject jo = new JSONObject(); inside the loop and it should work fine.
Place JSONObject jo = new JSONObject(); inside the loop:
while (products.readRecord())
{
JSONObject jo = new JSONObject();
String productID = products.get("user");
int j = Integer.parseInt(productID);
// etc
}

Categories