2

I want to parse a json data into a java object, then post it to a .jsp to then turn it back into a json object so I can put it into a javascript array.

Here is an example of the data I want to parse:

"LoanList" = [ {"Loan" : "One","Lat" : "35.65365", "Lng" : "123.1331" , "Bal" : "4565" ,  "Address" : "Address 1" , "Delinquency" : "True')]

After reading about it, I decided to use gson to parse the data: After reading other questions about this topic, I wrote two classes.

class1.java

import java.util.ArrayList;

public class JSON1 {

    ArrayList<innerData> Loanlst;


    public ArrayList<innerData> getLoanlst() {
        return Loanlst;
    }
    public void setLoanlst(ArrayList<innerData> Loanlst) {
        this.Loanlst = Loanlst;
    }
}

class2.java

import java.math.*;

public class innerData {
public String loan;
public BigDecimal lat;
public BigDecimal lng;
public BigDecimal bal;
public String addrs;
public String delinq;

public String getLoan() {
    return loan;
}

public void setLoan(String loan){
    this.loan = loan;
}

public BigDecimal getLat() {
    return lat;
}

public void setLat(BigDecimal lat){
    this.lat = lat;
}

public BigDecimal getLng() {
    return lng;
}

public void setLng(BigDecimal lng){
    this.lng = lng;
}

public BigDecimal getBal() {
    return bal;
}

public void setBal(BigDecimal bal){
    this.bal = bal;
}

public String getAddrs() {
    return addrs;
}

public void setAddrs(String addrs){
    this.addrs = addrs;
}


public String getDelinq() {
    return delinq;
}

public void setDelinq(String delinq){
    this.delinq = delinq;
}
}

Here is where I am stuck, Where do I create my new Gson() to parse the data before I send it?

tskuzzy
  • 35,812
  • 14
  • 73
  • 140
stacktraceyo
  • 1,235
  • 4
  • 16
  • 22

2 Answers2

3

Using your class you should be able to do something like:

InnerData obj = new InnerData(...);//fill in with data
Gson gson = new Gson();

// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);

check an example here and here

Tip: try creating a main class to run it separately.

Fawix
  • 469
  • 1
  • 8
  • 15
2

try this: JsonParser parser = new JsonParser(); JsonObject jsonObject=parser.parse("your string").getAsJsonObject();

also if it is a jsonArray ,change getAsJsonObject to getAsJsonArray

also jackson offers an easy to to parser string to json you can search jackson apache

fleture
  • 91
  • 1
  • 7