Java return JSONArray - java

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.

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.

How to add object to JSONArray

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+"]";
}
}

How do I convert a java class that has an arraylist to json

I use the Gson library and I have a class that has an arraylist as one of its members.
I add different object types to this arraylist then I serialize it to json
public class MethodParameter {
private String className;
private String methodName;
private ArrayList parameters;
public MethodParameter(){
parameters = new ArrayList();
}
public String getClassName(){
return className;
}
public String getMethodName(){
return methodName;
}
public List<Object> getParameters(){
return parameters;
}
public void setClassName(String value){
className = value;
}
public void setMethodName(String value){
methodName = value;
}
public void setParameters(ArrayList value){
parameters = value;
}
}
Then I convert as follows:
Gson gson = new Gson();
java.lang.reflect.Type type = new TypeToken<MethodParameter>() {}.getType();
String json = gson.toJson(mp, type);
but all I get is :
{"className":"MainClass","methodName":"Test","parameters":[]}
Parameters is an arraylist to which I add classes of different types. How do I get it to create the correct json result?
I tried your code and 2 things,
define the MethodParameter.parameters as a list (just a best practice)
the issue may be in the way you are manipulating the list in the MethodParameter object...
anyway here is a snippet working as you want it to do:
Example:
public static void main(String[] args) {
MethodParameter mp = new MethodParameter();
mp.setClassName(String.class.getCanonicalName());
mp.setMethodName("replace");
List<String> parametersList = new ArrayList<String>();
parametersList.add("target");
parametersList.add("sequence");
mp.setParameters(parametersList);
//
Gson gson = new Gson();
java.lang.reflect.Type type = new TypeToken<MethodParameter>() {
}.getType();
String json = gson.toJson(mp, type);
System.out.println(json);
}
but in my opinion you can generate the json by just doing this:
System.out.println(gson.toJson(mp, MethodParameter.class));

converting json into java object for a array with mixed types

My json string looks like the following:
{
"text": ["foo",1,"bar","2",3],
"text1": "value1",
"ComplexObject": {
.....
}
}
I have a pojo defined like this:
class MyPojo {
List<String> text;
String text1;
ComplexObject complexObject;
}
I use google gson and am able to get my java object populated properly. The problem here is that the field text is an array of mixed types (string and int). So all the entries there are converted into String and i am not able to figure out which entries in the array is a string vs int. I cant use parseInt since the entries in the original array may have "2" as well as 3.
Is there a way for me to get the right instance type of the fields in my array after converting into java object.
SOLUTION
So i implemented the solution using gson the round about way using the JsonDeserializer. And then i tried using jackson. Guess what jackson supports serializing/deserializing the mixed array type by preserving the data types.
ObjectMapper mapper = new ObjectMapper();
MyPojo gmEntry = mapper.readValue(json, new TypeReference<MyPojo >(){});
And i can basically fetch the List<Object> and do an instanceof to check for the datatype.
Shame on you gson!!
By having a custom class and adding a type adapter u can manipulate the string (json.toString() returns with the '"' quotes, so you can see if its a string or not.
Output: (the classes seem correct)
class test.Main$StringPojo pojo{object=foo}
class test.Main$IntPojo pojo{object=1}
class test.Main$StringPojo pojo{object=bar}
class test.Main$StringPojo pojo{object=2}
class test.Main$IntPojo pojo{object=3}
public static void main(final String[] args){
String str = "{\n" +
" \"text\": [\"foo\",1,\"bar\",\"2\",3],\n" +
" \"text1\": \"value1\" }";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(pojo.class, new JsonDeserializer<pojo>() {
#Override
public pojo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
return new IntPojo(Integer.parseInt(json.toString()));
} catch (Exception e) {
return new StringPojo(json.getAsString());
}
}
});
MyPojo myPojo = builder.create().fromJson(str, MyPojo.class);
for (pojo pojo : myPojo.text) {
System.out.println(pojo.getClass() + " " + pojo.object);
}
}
public static abstract class pojo{
protected Object object;
public pojo() {
}
#Override
public String toString() {
return "pojo{" +
"object=" + object +
'}';
}
}
public static class StringPojo extends pojo{
public StringPojo(String str) {
object = str;
}
}
public static class IntPojo extends pojo{
public IntPojo(int intt) {
this.object = intt;
}
}
public static class MyPojo {
List<pojo> text;
String text1;
}
As you wrote - you defined: List<String> text; but that list also contains integers.
Java is strongly typed, please consider to either declare the List as List<Object> (less preferable) or creating a JSON list that contains only a single type of variable (more preferable).
You can create an abstract class ItemType (for use as array item type) and inherits from it two wrapper classes: one for int type and another for string type.
abstract class ItemType {
protected Object value;
}
class IntType extends ItemType {
IntType(Integer value){
this.value = value;
}
}
class StringType extends ItemType {
IntType(String value){
this.value = value;
}
}
Try this List<ItemType> text;
The above situation can be achived by using TypeAdapter of Gson API.
Please follow : https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types
Not sure if this is what you need, but this is the code I use for parsing JSON.
static public void newsParser(String urlString, String targetObject) throws FileNotFoundException, IOException
{
URL url = new URL(urlString);
JSONParser parser=new JSONParser();
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
Object obj;
try
{
obj = parser.parse(br);
//JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) obj;
Iterator<?> i = jsonArray.iterator();
while (i.hasNext())
{
slide = (JSONObject) i.next();
newsInfo = (String)slide.get(targetObject);
System.out.println(newsInfo);
newsTitles.add(newsInfo);
}
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

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

Categories