0

I need to convert JSON string to Object[].

I tried with link1 and link2 and did not help me.

Code how i get JSON string:

public static String getListJsonString() {
    String getListsUrl = BASE_URL + "lists";
    String result = "";
    try {
        URL url = new URL(getListsUrl);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + getAuthStringEnc());
        InputStream is = urlConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        result = sb.toString();
        System.out.println(result);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

This is example of my JSON:

enter image description here

And after i must fill ChomboBox on this way (this is example):

Object[] lists = getLists();
for(Object list : lists){
    System.out.println("fill combobox");
}
Hrvoje
  • 696
  • 7
  • 22
  • What have you tried and what did not work? – Himanshu Bhardwaj Aug 24 '18 at 08:41
  • 2
    You need to provide the JSON string you are converting and show what you tried and how it failed. – Karol Dowbecki Aug 24 '18 at 08:41
  • `Object[] obj = new Object[] { str };` If this is not what you are looking for specify what you expect. – Henry Aug 24 '18 at 08:42
  • What do you mean by `did not help me` did you get an error? If so provide it. Was the output not the desired one? If so provide the output you got and specify what's wrong with it. What is the code that produced the problem? Did you make sure the JSON is valid? – Bernhard Aug 24 '18 at 08:43

3 Answers3

2

You can use Gson, TypeToken and JSONObject, example:

final static Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
final Type objectType = new TypeToken<Object>(){}.getType();

JSONObject obj = new JSONObject(result);

Vector<Object> lists = gson.fromJson(obj.toString(), objectType); 
byte
  • 112
  • 7
1

I suggest you should be using jackson lib. I linked a great quick tutorial that I find really clear and useful.

The idea behind jackson lib is that JSON format is a stringified Object format so you should be able to map it properly to java POJOs easily. (POJO = Plain old java object, which is an object with some fields, maybe some annotations on top of your fields and finally just getters and setters).

You can auto generate Jackson annotated POJOs classes from a json string using this link : http://www.jsonschema2pojo.org/ (just select "JSON" instead of "JSON SCHEMA", and maybe tune the other parameters depending on your need).

Louis-wht
  • 535
  • 5
  • 17
0

I can feel your pain sometimes it's hard to get a quick example up and running.

This is a very simple example how you can read your json document using Jackson library. You need a minimum of jackson-annotations-x.y.z.jar, jackson-core-x.y.z.jar and jackson-databind-x.y.z.jar files in a classpath.

https://github.com/FasterXML/jackson-databind/

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

public class TestJSON1 {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonObj;

        String jsonStr = "{ \"list\": [ "
            + " {\"id\":\"1\", \"name\":\"test1\"}, "
            + " {\"id\":\"2\", \"name\":\"test2\"}, "
            + " {\"id\":\"3\", \"name\":\"test3\"} "
            + "]}";

        jsonObj = mapper.readTree(jsonStr);
        System.out.println(jsonObj.get("list"));

        JsonNode jsonArr=jsonObj.get("list");
        int count=jsonArr.size();
        for (int idx=0; idx<count; idx++) {
            jsonObj = jsonArr.get(idx);
            System.out.println( jsonObj.get("id").asText()+"="+jsonObj.get("name").asText() );
        }
    }

}
Whome
  • 10,181
  • 6
  • 53
  • 65