0

I'm new to JSON so please excuse my ignorance. I need to get a JSON Object like this:

jsonString =
{
    "Key": {"AppID":"19","Username":"sompoRoot","Password":"11223344"},
    "deviceList": ["43ab48a0eb9f950d9c2498f8c2cfa1e5b8a62687479cfad849bbc455b88e67b6",
                   "43ab48a0eb9f950d9c2498f8c2cfa1e5b8a62687479cfad849bbc455b88e67b6"],
    "aps": {"alert":"merhaba dunya","sound":"default","badge":"10",
    "dictionaryArray":["a","b"],
    "production":"false"}   
}

I will get AppID, UserName and Password from database. deviceList is something like that :43ab48a0eb9f950d9c2498f8c2cfa1e5b8a62687479cfad849bbc455b88e67b6, 43ab48a0eb9f950d9c2498f8c2cfa1e5b8a62687479cfad849bbc455b88e67b6... and I will get alert, sound, badge dictionaryArray and production from text input. I got and convert String these parameter. I search from internet but I think it is more complex, how can I get like that JSON, Thank you.

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
Fatih
  • 59
  • 1
  • 4
  • 11
  • Are all your desired fields concatenated in a single String? Or do you have a separate String for each of them? – Raul Rene Sep 06 '13 at 11:27
  • Go to json.org. At the bottom of the page is a list of JSON toolkits for different languages. There are at least a dozen to choose from for Java. (Basically, you put the data into Java maps and lists to correspond to the JSON "objects" and "arrays" you need, then tell the JSON toolkit to turn that structure into a JSON string.) – Hot Licks Sep 06 '13 at 11:28
  • @RaulRene I have seperate String for each of them. – Fatih Sep 06 '13 at 11:29
  • Until i am home and can provide you with a specific solution i recomend: - see this post: http://stackoverflow.com/questions/5245840/how-to-convert-string-to-jsonobject-in-java - Out of personal practise: Read about the JSON Format itself, there are like 3 or 4 ways one could marshall/ unmarshall for example a Array of Objects <-> JSON (it will spare you lots of time if this is a bigger project for you) – JBA Sep 06 '13 at 11:33

4 Answers4

3

You said in a comment that you have a separate String for each of the fields. I would suggest building a class containing all your desired fields, in the following manner (as aps appears to be a separate entity, create a separate class for it):

public class MyClass {
    private String key;
    private List<String> deviceList;
    private Aps aps;
}

public class Aps {
    private String alert;
    private String sound;
    private long badge;
    private List<String> dictionaryArray;
    private boolean production;
}

There are several libraries to help you convert your Java objects into JSONs, and one of them is Jackson's ObjectMapper class. You can download the library from their website or if you are using Maven in your project you can find the dependency on mvnrepository.com.

Using the ObjectMapper:

ObjectMapper objectMapper = new ObjectMapper();
MyClass myClass = new MyClass();
// .. populate the fields
String jsonString = objectMapper.writeValueAsString(myClass);

You will have to surround that in a try-catch block. And that's about it: jsonString now holds your fields converted to a JSON String.


Edit: instead of Jackson you could use Google GSON, that works in about the same manner.

Raul Rene
  • 10,014
  • 9
  • 53
  • 75
2
package com.stackoverflow.q1688099;

import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }

    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }
}

check out this link

Community
  • 1
  • 1
Nambi
  • 11,944
  • 3
  • 37
  • 49
1

You can use a JSON library for java (GSON, Jettison etc). After that add you data in a Map object (nested structure) and use the utility methods in the library to convert it to JSON.

Find example using Jettison

   JSONObject json = new JSONObject();

   JSONObject jsonKey = new JSONObject();
   jsonKey.put("AppID", 19);
   jsonKey.put("Username", "usrname");
   jsonKey.put("Password", "passwd");


   String[] deviceList = {"value1", "value2"};

   json.put("key", jsonKey);
   json.put("deviceList", deviceList);

   String finalJson = json.toString();
hanish.kh
  • 517
  • 3
  • 15
0

You Could try gson from google =) I think it is pretty easy and fast -> https://code.google.com/p/google-gson/

lcestari
  • 178
  • 5