Johnny
Johnny

Reputation: 103

How do I correctly format this gson.fromJson call?

My array is a list of events and I need to intialize each event with its information from my JSON file. I created this simple setup based on what I found on other answers here using GSON but I'm super confused on how the gson.fromJSON call works

I have 3 variables in Event that I want to retrieve from the JSON file - start date, end date, and summary. Does fromJSON automatically assign them from the JSON to the their values in Event?

this is what my json file looks like:

[
  {
    "dtstart": "10/31/2015",
    "dtend": "10/31/2015",
    "summary": "Halloween"
  },
.....
]

there are about half a dozen more of those such events.

This is my code in my Main java file:

public class MainActivity extends AppCompatActivity {


Event[] mobileArray;
Gson gson = new Gson();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader("academiccalendar.json"));
    } catch (FileNotFoundException e){
        e.printStackTrace();
    }

    mobileArray = gson.fromJson(br, Event[].class);

And this is my event class:

public class Event {
    private String dtsart;
    private String dtend;
    private String summary;

I know this must make me look like a complete fool. But I can't wrap my head around how to turn that JSON file into an array of events. Could someone please point me in the right direction? I've tried a lot of other methods on StackOverflow and elsewhere but none seem right for my situation

EDIT: Removed the loop I had for mobileArray with the line Gil posted. IMPORTANT to future people reading this message - fromGSON was NOT initializing the same named variables in my Event class and I figured out it was because they were set to private and I was trying to assign them from my main activity class. I had to change to public

Upvotes: 0

Views: 179

Answers (1)

Gilad Eshkoli
Gilad Eshkoli

Reputation: 1253

Why do you need that for loop ?

Did you try this line of code:

mobileArray = gson.fromJson(br, Event[].class);

try to get the whole array at once, instead of one object at a time.

Also, what is the error that you get when trying to do so?

And for your question about fromJson, the answer is yes, it assign them automatically if the variables names are the same in the POJO and in the JSON file.

Upvotes: 3

Related Questions