How to add object to JSONArray - java

I want to add an object to an array. If the data of other_amount is more than zero I want to add one object more. If it's equal to zero, it should add nothing. This is my code:
JSONArray acc_data = new JSONArray();
Map<String, Object> myaccount = new LinkedHashMap<>();
for (int i = 0; i < mpay.size(); i++) {
if(other_amount>0){
myaccount.put("poAccount", other_account);
myaccount.put("poAmount", other_amount);
system.out.println(myaccount);
//{poAccount=050017, poAmount=12}
}
myaccount.put("poAccount", amount_account);
myaccount.put("poAmount", amount);
system.out.println(myaccount);
//{"poAccount":"050016","poAmount":"800"}
acc_data.add(myaccount);
system.out.println(acc_data);
//[{"poAccount":"050016","poAmount":"800"}]
}
But I need it like this:
//[{"poAccount":"050016","poAmount":"800"},{poAccount=050017, poAmount=12}]
please help me to resolve it.

You shouldn't use map for your case.
When your put the pair with existing in map key, the pair will be overwrited.
For example
map.put ("k1","v1");
Map contains one pair "k1":"v1"
The next call
map.put ("k1","newV1");
The first pair will be overwrited and map still contains 1 pair: "k1":"newV1"
For your case it's better to define simple POJO class with 2 fields poAccount and poAmount. And add them to the JSONArray

The approach you are following, it will not serve your requirement. You should use pojo to store the records and then populate the Json Array. You can have a look at this code and modify as per your requirements.
public class Test {
public static void main(String[] args) {
Mypojo mypojo = new Mypojo();
Gson gson = new Gson();
JSONArray records = new JSONArray();
for (int i = 0; i < 1; i++) {
if (5 > 0) {
mypojo.setPoAccount("050017");
mypojo.setPoAmount("12");
JSONObject objects = new JSONObject(gson.toJson(mypojo));
records.put(objects);
}
mypojo.setPoAccount("050016");
mypojo.setPoAmount("800");
JSONObject objects = new JSONObject(gson.toJson(mypojo));
records.put(objects);
}
System.out.println(records);
}
}
Mypojo Class :
public class Mypojo
{
private String poAmount;
private String poAccount;
public String getPoAmount ()
{
return poAmount;
}
public void setPoAmount (String poAmount)
{
this.poAmount = poAmount;
}
public String getPoAccount ()
{
return poAccount;
}
public void setPoAccount (String poAccount)
{
this.poAccount = poAccount;
}
#Override
public String toString()
{
return "ClassPojo [poAmount = "+poAmount+", poAccount = "+poAccount+"]";
}
}

Related

How to pull values from a json object that looks like "key":[10,12,56] with Java

In wordpress an Api I use returns the tags' ids in an odd way, it returns in this ways:
"tags":[50,51,54]
I have never seen any Json that doesn't look like "key":"value", and I got no clue how to parse it...
I hope you can help, Thank you!
Update:
My bad, the example I posted was not a full json, it looks like that:
{"categories":[2,8],"tags":[50,51,54]}
The [] indicate that the tags are stored as an array. You can use JSONObject.getJSONArray() to access the array as a JSONArray object, then use .getInt() to retrieve the values. For example:
String jsonString = "{\"categories\":[2,8],\"tags\":[50,51,54]}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray tagsArray = jsonObject.getJSONArray("tags");
// Transfer JSONArray to an int[] array.
int tags[] = new int[tagsArray.length()];
for (int i=0; i<tagsArray.length(); i++) {
tags[i] = tagsArray.getInt(i);
}
You can create a class for this json string and parse the json with just one line of code as shown in main method.
public class Example {
private List<Integer> categories = null;
private List<Integer> tags = null;
public List<Integer> getCategories() {
return categories;
}
public void setCategories(List<Integer> categories) {
this.categories = categories;
}
public List<Integer> getTags() {
return tags;
}
public void setTags(List<Integer> tags) {
this.tags = tags;
}
public static void main(String[] args) {
String str = "{\"categories\":[2,8],\"tags\":[50,51,54]}";
Example example = new Gson().fromJson(str, Example.class);
System.out.println(example.getCategories());
System.out.println(example.getTags());
}
}
You need to have gson library for this and have this import,
import com.google.gson.Gson;
Hope this works for you.

Parsing JSON Object with no identifier with Jackson

I am getting JSON from a web service, the JSON response I'm getting is:
{
"response":"itemList",
"items":[
"0300300000",
"0522400317",
"1224200035",
"1224200037",
"1547409999"
]
}
I am looking to get each id within the items array. The problem is I'm unsure how to parse this with Jackson when there are no identifiers for the id in the items array. My understanding is I could have an item class with a variable id and #JsonProperty ("id"), but I don't know how to proceed. I need to display these ids in a list (which I can do no problem once I have the data.
Could someone please point me in the right direction.
Thank you.
You could deserialize into something like
public class MyData {
public String response;
public List<String> items;
}
(this will also work if you have private fields with public set methods). Or if you don't mind having jackson-specific annotations in your data classes, you can leave them as non-public and annotate them:
public class MyData {
#JsonProperty
String response;
#JsonProperty
List<String> items;
}
either way, use this to parse:
import com.fasterxml.jackson.databind.ObjectMapper;
//...
MyData data=new ObjectMapper().readValue(jsonStringFromWebService, MyData.class);
You can Convert the JSON String to JSON object, and identify the array and get the IDs..
String josn = "{\"response\":\"itemList\", \"items\":[\"0300300000\",\"0522400317\",\"1224200035\",\"1224200037\",\"1547409999\"]}";
JSONObject jsonObject = new org.json.JSONObject(josn);
JSONArray itemsArray = jsonObject.getJSONArray("items");
System.out.println("Item - 1 =" + itemsArray.getString(0));
class Something {
public String response;
#JsonCreator
public Something(#JsonProperty("response") String response) {
this.response=response;
}
public List<String> items= new ArrayList<String>();
public List<String> addItem(String item) {
items.add(item);
return items;
}
}
and then:
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String json = "{\"response\":\"itemList\",\"items\":[\"0300300000\",\"0522400317\"]}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, Something.class);
}
I think so, you want this :
ArrayList<String> notifArray=new ArrayList<String>();
JSONObject jsonObj= new JSONObject (resultLine);
JSONArray jArray = jsonObj.getJSONArray("items");
for (int i = 0; i < jArray.length(); i++) {
String str = jArray.getString(i);
notifArray.add(str);
}

Java Object Scope

I am trying to create an object based on a condition, therefore the object creation is within the conditional's scope, however I need to see the object outside of that scope. I thought adding it to a Map would work, but it doesn't. Consider the following example:
TestModel.java
public class TestModel {
private String text;
public void setText(String text){
this.text = text;}
public String getText(){
return this.text;}
}
ScopeTest.java
import java.util.*;
class ScopeTest {
public static void main(String[] args) {
TestModel testModel;
Map<String, Object> myModel = new HashMap<String, Object>();
for (int i=1; i<2; i++){ // if a certain condition is met, create an object as below
testModel = new TestModel();
testModel.setText("test text");
myModel.put("test", testModel);
}
for (Map.Entry<String, Object> entry : myModel.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
System.out.println("key=" + key); // I can see the key value
System.out.println("value.getText()=" + value.getText()); // but can't see testModel object. I am not sure how to resolve.
}
}
}
cheers,
Geofrey Rainey.
You have to cast the Object value with your Class. Like this.
System.out.println("value.getText()=" + ((TestModel) value).getText());
If you dont want to cast the object then you can use like this.
class ScopeTest {
public static void main(String[] args) {
TestModel testModel;
Map<String, TestModel> myModel = new HashMap<String, TestModel>();//Use TestModel
instead of object
for (int i=1; i<2; i++){
testModel = new TestModel();
testModel.setText("test text");
myModel.put("test", testModel);
}
for (Entry<String, TestModel> entry : myModel.entrySet()) {
String key = entry.getKey();
TestModel value = entry.getValue();
System.out.println("key=" + key);
System.out.println("value.getText()=" + value.getText());
}
}
}
You should cast the Object into your model.
TestModel value = (TestModel) entry.getValue();
I think you might have to cast the object returned by the HashMap to be a TestModel before you can use a method of that class.
Why not just use TestModel as generic type of value in your Map like below?
Map<String, TestModel> myModel = new HashMap<>();
// ^^^^^^^^^ - instead of Object
This way you can iterate over your map with
for (Map.Entry<String, TestModel> entry : myModel.entrySet()) {
...
}
and you will be able to store value in
TestModel value = entry.getValue();
without needing to cast it. Now since type of value reference will be TestModel compiler will let you use its methods like getText() without problems.
System.out.println("value.getText()=" + value.getText());
Also I am not sure why you are using loop if you want to iterate over it once. Simple if would be better. Another thing is using Map to hold one element seems unnecessary. You can just use one reference like
boolean someCondition = true;
TestModel testModel = null;
if (someCondition) { // if a certain condition is met, create
testModel = new TestModel();
testModel.setText("test text");
}
if (testModel!=null){
System.out.println(testModel.getText());
}

Java return JSONArray

I'm trying to create a jsonarray from a Map in java. I'm passing it in to a javascript variable. But i don't know why the mac and status are blank, any help much appreciated.
what i need:
[{"12345":{"mac":"FFFFFFFF", "status":"ON"}]
What i am getting with my current code:
[{"12345":{}]
Here is my code,
public class Details {
public JSONArray getResult() {
return JSONArray.fromObject(this.det);
}
public Map det = new HashMap();
public results() {
ResultSet rs;
det.put(rs.getString(1), new NodeDetails(rs.getString(2), rs.getString(3));
}
class NodeDetails {
public final String MAC;
public final String status;
public NodeDetails(final String ma,final String st) {
this.MAC = ma;
this.status = st;
}
}
}
Do you have any limitation on any library? I mean are you using JSON library from http://org.json or which library?
Following is the code that I've tried using JSON library from http://org.json:
public class Test {
public static class NodeDetails {
public final String MAC;
public final String status;
public NodeDetails(final String ma, final String st) {
this.MAC = ma;
this.status = st;
}
}
public static void main(String[] args) throws Exception {
Map<String, NodeDetails> map = new HashMap<String, NodeDetails>();
// do something with you ResultSet? and populate the map ;)
map.put("12345", new NodeDetails("FFFFFF", "ON"));
JSONObject jsonMap = new JSONObject();
for (Map.Entry<String, NodeDetails> entry : map.entrySet()) {
JSONObject object = new JSONObject();
object.put(entry.getValue().MAC, entry.getValue().status);
jsonMap.put(entry.getKey(), object);
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonMap);
System.out.println(jsonArray.toString());
}
}
You can read more about the API here:
http://json.org/java/
JsonArray.fromObject-- Creates a JSONArray.
Inspects the object type to call the correct JSONArray factory method. Accepts JSON formatted strings, arrays and Collections.
And Map which you are passing is not JSON formatted. So try using add() method on JsonArray Or put() method on JsonObject.

Parsing JSON ARRAY

I'm working on json parsing and I got a problem.
This is my JSON:
"cards":[
{
"id":"bgyr6gh5yr6154",
"checkItemStates":[
],
"closed":false,
"desc":"",
"due":"2012-06-13T10:00:00.000Z",
"idBoard":"4v454g5r1515",
"idChecklists":[
],
"idList":"16562562526",
"idMembers":[
"2848f4g85t15"
],
"idShort":15,
"labels":[
],
I can get all information in the JSON Array cards (e.g "closed", "due",...)
I'm doing for instance,
JSONArray msg2 = (JSONArray) all.get("cards");
then
String boardId = (String) monobjet.get("closed");
and it works fine!
BUT
I don't know how to get "idMembers" !
Any idea, because it's array in a array?
JSONArray msg2 = (JSONArray) all.get("cards");
then
for (int i2 = 0; i2 < size2; i2++) {
myobject = (JSONObject) msg2.get(i2);
listTemp2.add(jsonObecjtToMyData(myobject));
}
String boardName = (String) monobjet.get("name");
For complex json objects such as the one given, I will strongly recommend gson which will do all the task for you.For example:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Map map = gson.fromJson(inputField.getText(),Map.class);
Now, map conatains all the things you need, so iterate through the map get the idMembers put it in a list and while you are putting it typecast it to string or any datatype that is fit.
You can individually typecast but not an array. So this will compile and run:
public class MainApp {
public Object obj[]={"foo","loo"};
public Object obj2 = "soo";
public static void main(String[] args) {
MainApp mainApp = new MainApp();
String name = (String) mainApp.obj2;
System.out.println(name);
}
}
Some food for thought:
JSONArray is an object. How would the json handler that you are using would know that it is a JSONArray or list?
Can we do something like this?:
public class MainApp {
public Object obj[]={"foo","loo"};
public static void main(String[] args) {
MainApp mainApp = new MainApp();
String name[] = (String[])mainApp.obj;
for(String str : name){
System.out.println(str);
}
}}
Please use gson and save yourself a lot of pain.Also for complex pojos you can use ObjectMapper.

Categories