-2

I am new to JSON data format and java programming language; hence, I cannot find a valid answer. Actually, I have to read this API https://www.doviz.com/api/v1/currencies/all/latest, and obtain some important contents from this API. Hence, I decided to use google's GSON class, and I wrote this code.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Scanner;
import com.google.gson.Gson;


public class Main {

    public static void main( String[] args ) throws Exception{

        String line = "";
        String jsonString = "";
        URL myUrl = new   URL("https://www.doviz.com/api/v1/currencies/all/latest");
        BufferedReader reader = new BufferedReader( new InputStreamReader(myUrl.openStream()) );

        while( (line = reader.readLine()) != null ){
            System.out.println(line);
            jsonString += line;
        }
        reader.close();

        jsonString = jsonString.substring(1, jsonString.length() - 1);

        Gson gson = new Gson();
        Currency json = gson.fromJson(jsonString, Currency.class);
   }
}


public class Currency {

    public double getSelling(){
        return selling;
    }

    public double getBuyiing(){
        return buying;
    }

    public String getCode(){
        return code;
    }

    private double selling;
    private transient long update_date;
    private transient int currency;
    private double buying;
    private transient double change_rate;
    private transient String name;
    private transient String full_name;
    private String code;
}

This code causes error, and as far as I guess, the main reason for the errors is that I do not put backslash in son string like this: "{\"brand\":\"Jeep\", \"doors\": 3}"

What I am wondering is why we need to put these backslash ?

Chirag Jain
  • 628
  • 11
  • 24
Goktug
  • 855
  • 1
  • 8
  • 21
  • What's the error? – Dici Sep 22 '18 at 10:48
  • "This code causes error" any reason you can't include error message in the question? Does it contain some sensitive information like passwords or other? In that case you can replace them with `PASSWORD` instead of real content. – Pshemo Sep 22 '18 at 11:00
  • BTW `jsonString += line;` is very inefficient for longer strings because for each new line it needs to copy all previous content and then add to it new line. Take a look at [Why StringBuilder when there is String?](https://stackoverflow.com/q/5234147) – Pshemo Sep 22 '18 at 11:06

2 Answers2

1

There are 2 things to mention.

  1. The " character is the String delimiter. A String starts at a " mark, and ends at the next one. (When initializing it explicitly, not using other variables) If you want to include " character in your String, you need to escape it like \" - so Java knows that it is not the end of the String, just a part of the content.

  2. In JSON you should use single quotes ' - many libraries accept double quotes also, but it is not correct actually, and if any api complains about them, the API is right. So your payload should look like {'brand': 'Jeep', 'doors': 3} I mean the other way around of course.

skandigraun
  • 741
  • 8
  • 21
0

When you receive a JSON output from the api, you can directly use the output and can deserialize it. You don't need to have escape characters in the json string. They are required when you define the json string yourself. For example String s = "{\"current_user_url\"}"; because it is the compiler which forces you to escape it. But the json output you are getting as an API response is in a variable and if type of variable and the content you are assigning to it are same then compiler can't compain about that.

Now, I have used your code only but used the Github public API and I am able to deserialize the output json without any operation on the output string whatsoever like escaping the "" or changing "" to ''.

class Github {
    private String current_user_url;
    private String authorizations_url;

    public String getCurrent_user_url() {
        return current_user_url;
    }
    public void setCurrent_user_url(String current_user_url) {
        this.current_user_url = current_user_url;
    }
    public String getAuthorizations_url() {
        return authorizations_url;
    }
    public void setAuthorizations_url(String authorizations_url) {
        this.authorizations_url = authorizations_url;
    }
}

public static void main(String[] args) throws IOException, ClassNotFoundException {

        String line = "";
        String jsonString = "";
        URL myUrl = new   URL("https://api.github.com");
        BufferedReader reader = new BufferedReader( new InputStreamReader(myUrl.openStream()) );

        while( (line = reader.readLine()) != null ){
            //System.out.println(line);
            jsonString += line;
        }
        reader.close();

        System.out.println(jsonString);


        Gson g = new Gson();
        Github gi = g.fromJson(jsonString, Github.class);
        System.out.println(gi.getAuthorizations_url());
        System.out.println(gi.getCurrent_user_url());
}

I also defined the json string myself and desrialized it using GSON. In this case while defining the json string I needed to escape the double quotes as shown below:

String s = "{\"current_user_url\":\"http://test.com/user\"}";

Gson g = new Gson();
Github gi = g.fromJson(s, Github.class);
System.out.println(gi.getCurrent_user_url());

Also, JSON strings should contain double quotes only and if you use single quotes then you may get an error.

Yug Singh
  • 3,112
  • 5
  • 27
  • 52