Search code examples
javajsongsonjson-deserialization

Reading API and GSON Class


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 ?


Solution

  • 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.