2

In Java project I used WebSocket to get subscription and I get many different responses from socket as JSONArray, the one which I need looks as below:

[
  68,
  "te",
  [
    80588348,
    1508768162000,
    0.01569882,
    5700.8
  ]
]

How should look JAVA object for this response? How can I convert it to this object?

[
  68, <- Integer
  "te", <- String
  [
    80588348, <- Long
    1508768162000, <- Long
    0.01569882, <- Double
    5700.8 <- Double
  ]
]

There is one problem that there are other responses like:

{"event":"subscribed","channel":"trades","chanId":68,"symbol":"tBTCUSD","pair":"BTCUSD"}

And when I try convert it by new JSONArray(response) it throws org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1].

How to get and convert this fields which I need(the first response example) ?

I want get something like this:

public class Details{
   public Long id;
   public Long timestamp;
   public Double amount;
   public Double price;
}

public class Response{
   public Integer id;
   public String type;
   public Details details;
}
ACz
  • 567
  • 5
  • 22
  • Are you using any frame works? – Vipin CP Oct 24 '17 at 10:03
  • That isn't an object but just a list, i.e. in Java both the outer and the inner list would probably be either a `List` or an array `Object[]`. – Thomas Oct 24 '17 at 10:04
  • I received `String` and I tried convert it by `new JSONArray(responseString)`. It returned me JSONArray but I want to get java object which should contain Integer, String and second object inside with 4 fields. – ACz Oct 24 '17 at 10:06
  • 1
    If your response is fixed format, i recommend you to use objectmapper to transfer it to Java Object directly – PSo Oct 24 '17 at 10:27
  • @PSo Can You help with some example? – ACz Oct 24 '17 at 10:27
  • 1
    @ACz Given a simple example for you, if you are having array of response, you can just read it as list and do some transformation. – PSo Oct 24 '17 at 10:32

2 Answers2

2

The parser class as requested:

public class JsonParser {
    public static Response toJavaObject(String str) {
        String[] fields = str.split(",");
        Response res = new Response();
        res.setId(Integer.valueOf(fields[0].substring(1)));
        res.setType(fields[1].replaceAll("\"", ""));
        Details dtl = new Details();
        dtl.setId(Long.valueOf(fields[2].substring(1)));
        dtl.setTimestamp(Long.valueOf(fields[3]));
        dtl.setAmount(Double.valueOf(fields[4]));
        dtl.setPrice(Double.valueOf(fields[5].substring(0, fields[5].length() - 2)));
        res.setDetails(dtl);

        return res;
    }
}

class Details {
    public Long id;
    public Long timestamp;
    public Double amount;
    public Double price;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }

    public Double getAmount() {
        return amount;
    }

    public void setAmount(Double amount) {
        this.amount = amount;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

class Response {
    public Integer id;
    public String type;
    public Details details;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Details getDetails() {
        return details;
    }

    public void setDetails(Details details) {
        this.details = details;
    }
}

To make use of this JsonParser,

for example in your code now:

public static void main(String args[]) {
    String str = "[68,\"te\",[80588348,1508768162000,0.01569882,5700.8]]";
    Response res = JsonParser.toJavaObject(str);
    // your logic below...
}
PSo
  • 958
  • 9
  • 25
  • Aww ok, so only manually way by setting fields is possible? No easiest way? – ACz Oct 24 '17 at 11:02
  • 1
    Come on bro, can you just create a JsonParser.java , copy the above stuff inside, and call it when needed – PSo Oct 24 '17 at 11:03
  • Last question, How to distinguish which object is coming? As I told I get two different responses from the same source `[68,"te",[80588348,1508768162000,0.01569882,5700.8]]` and `{"event":"subscribed","channel":"trades","chanId":68,"symbol":"tBTCUSD","pair":"BTCUSD"}` but I need only the first one – ACz Oct 24 '17 at 11:09
  • 1
    Added, please just copy make a java class, and import it and use it directly, it is not thread safe but whatever. – PSo Oct 24 '17 at 11:09
  • 1
    @ACz you can tell the different by reading the first char, if it is "[", then use, if it is "{", ignore – PSo Oct 24 '17 at 11:10
  • Ok so all do manually, I think that there should be sobe libs to do it automatically :P But thanks! – ACz Oct 24 '17 at 11:11
  • @ACz please let me know if you find a way easier than this one lol – PSo Oct 24 '17 at 15:33
1

If your response is in fixed format,

example:

JSONString : {"color":"yellow","type":"renault"}

In Java, you can use the following code:

Car car = objectMapper.readValue(jsonString, Car.class);  

Where you have the Car class as:

public class Car {

    private String color;
    private String type;

    // standard getters setters
}
PSo
  • 958
  • 9
  • 25
  • It is bright but How to get it when I get response `[68,"te",[80588348,1508768162000,0.01569882,5700.8]]` ? It Looks as `JSONArray` – ACz Oct 24 '17 at 10:33
  • 1
    it is not a JSONArray, it is a standard JSONObject start with "[", which is an array struct – PSo Oct 24 '17 at 10:36
  • When I tried `new JSONObject(response)` it returned me `org.json.JSONException: A JSONObject text must start with '{' at 1 [character 2 line 1]` – ACz Oct 24 '17 at 10:37
  • 1
    you are having an array structured json object, which is uncommon nowadays, i guess the best way is to implement a json parser yourself in this format – PSo Oct 24 '17 at 10:39
  • Hmm I think about `Gson` but do not have idea how it should be converted – ACz Oct 24 '17 at 10:41
  • 1
    i did a little research and see: https://stackoverflow.com/questions/5034444/can-a-json-start-with – PSo Oct 24 '17 at 10:41
  • 1
    @ACz gson, jackson, json, all provided parsing for JSONObject, but not your kind of JSONObject... – PSo Oct 24 '17 at 10:42
  • Damn it. So there is no option to get it automatically and convert to object without manually? – ACz Oct 24 '17 at 10:44
  • 1
    If you are having input like that, it is not too difficult to write your own parser, give me like 3~5mins – PSo Oct 24 '17 at 10:48
  • Ok :) Thanks for Yours time! – ACz Oct 24 '17 at 10:49
  • added the parser, you can copy the method and change a little bit for your own use, such as return a Response Object and create your own method – PSo Oct 24 '17 at 11:01