I am getting this error when querying a URL and get a json object. My json:
{"status":1,"username":"admin","nombre":"Username","email":"example#example.cl","codigo_usuario":"1","hash":"2938632bfdklsngh","imagen":"05c151584cc1e9aa2985b5bd0a3a4cd2.jpeg"}
Create the User class
public class User {
private int status;
private String username;
private String nombre;
private String email;
private String codigo_usuario;
private String hash;
private String imagen;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getImagen() {
return imagen;
}
public void setImagen(String imagen) {
this.imagen = imagen;
}
public String getCodigo_usuario() {
return codigo_usuario;
}
public void setCodigo_usuario(String codigo_usuario) {
this.codigo_usuario = codigo_usuario;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User [status=" + status + ", username=" + username
+ ", nombre=" + nombre + ", email=" + email
+ ", codigo_usuario=" + codigo_usuario + ", hash=" + hash
+ ", imagen=" + imagen + "]";
}
}
And in my class, I make the request to the URL I have this code:
public static boolean authenticate(String username, String password){
boolean error = false;
User user = null;
try {
String request = Config.getText("URL_BASE")+Config.getText("URL_AUTHENTICATE")+username+"/"+password;
HttpURLConnection conn = (HttpURLConnection) new URL(request).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new Exception("Failed : HTTP error code : " + conn.getResponseCode());
}
user = new Gson().fromJson(new InputStreamReader(conn.getInputStream()), User.class);
System.out.println(user.toString());
conn.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return error;
}
And I get the exception. I saw other post with this same error and in most the error was the json format or class that did not have the same fields. Now, check well and everything should be OK. But for some reason I receive this error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:741)
at controller.WService.authenticate(WService.java:29)
at view.Login._verificarLogin(Login.java:77)
at view.Login$2.actionPerformed(Login.java:44)
I'm new to Java and try to consume a web service for data and use. I think this is my best option but still do not understand the error.
Related
I have an Api, Api = "http://retailapi.airtechsolutions.pk/api/login/admin#gmail.com/admin/"
I am new to Retrofit2, If some one can help me through my code
I have an Error while doing GET and POST Request
While Using Get Api: the Username and password are null
While Using Post Api: I am getting 404 Error code
Login Activity:
private JsonPlaceHolderApi jsonPlaceHolderApi;
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://retailapi.airtechsolutions.pk/api/login/admin#gmail.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
getLogin();
createPost();
}
private void getLogin()
{
Call<Login> call = jsonPlaceHolderApi.getLogin();
call.enqueue(new Callback<Login>()
{
#Override
public void onResponse(Call<Login> call, Response<Login> response)
{
if (!response.isSuccessful())
{
Log.i("Code: " , String.valueOf(response.code()));
return;
}
Login logins = response.body();
String content = "";
content += "UserName: " + logins.getUsername() + "\n";
content += "Password: " + logins.getPassword() + "\n";
content += "Status: " + logins.getStatus() + "\n";
content += "Description: " + logins.getDescription() + "\n\n";
Log.i("Read me", content);
}
#Override
public void onFailure(Call<Login> call, Throwable t)
{
Log.i("Error", t.getMessage());
}
});
}
private void createPost() {
Login login = new Login("New Name", "New Password");
Call<Login> call = jsonPlaceHolderApi.createPost(login);
call.enqueue(new Callback<Login>() {
#Override
public void onResponse(Call<Login> call, Response<Login> response) {
if (!response.isSuccessful())
{
Log.i("Code: " , String.valueOf(response.code()));
return;
}
Login loginResponse = response.body();
String content = "";
content += "Code: " + response.code() + "\n";
content += "UserName: " + loginResponse.getUsername() + "\n";
content += "Password: " + loginResponse.getPassword() + "\n";
content += "Status: " + loginResponse.getStatus() + "\n";
content += "Description: " + loginResponse.getDescription() + "\n\n";
Log.i("Read me",content);
}
#Override
public void onFailure(Call<Login> call, Throwable t) {
Log.i("Failure", t.getMessage());
}
});
}
Login Class:
String username;
String password;
int Status;
String Description;
public Login(String username, String password)
{
this.username = username;
this.password = password;
}
public String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
public int getStatus()
{
return Status;
}
public String getDescription()
{
return Description;
}
And An Interface Class Called JsonPlaceHolderApi
public interface JsonPlaceHolderApi
{
#GET("admin")
Call<Login> getLogin();
#POST("admin")
Call<Login> createPost(#Body Login login);
}
Starting with the GET issue, you are getting fields (Username and password) equals to null because they are not at the top level of your JSON, so, in order to fix the GET issue you need to create the following class :
LoginResponse
import com.google.gson.annotations.SerializedName;
public class LoginResponse {
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#SerializedName("Users")
User user;
#SerializedName("Status") int status;
#SerializedName("Description") String description;
}
Add a user class which will host all the user's data :
User
public class User {
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getClientno() {
return clientno;
}
public void setClientno(String clientno) {
this.clientno = clientno;
}
public String getCompanyno() {
return companyno;
}
public void setCompanyno(String companyno) {
this.companyno = companyno;
}
public String getUserno() {
return userno;
}
public void setUserno(String userno) {
this.userno = userno;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getRowno() {
return rowno;
}
public void setRowno(int rowno) {
this.rowno = rowno;
}
String clientno;
String companyno;
String userno;
String username;
String password;
int rowno;
}
Then update your JsonPlaceHolderApi interface to return a Call<LoginResponse> instead of Call<Login> :
#GET("admin")
Call<LoginResponse> getLogin();
#POST("admin")
Call<LoginResponse> createPost(#Body User login);
One more thing, replace both getLogin() and createPost() with the following :
private void getLogin() {
Call<LoginResponse> call = jsonPlaceHolderApi.getLogin();
call.enqueue(new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (!response.isSuccessful()) {
http://retailapi.airtechsolutions.pk/api/login/admin#gmail.com/
Log.i("Code: ", String.valueOf(response.code()));
return;
}
LoginResponse loginResponse = response.body();
String content = "";
content += "UserName: " + loginResponse.user.getUsername() + "\n";
content += "Password: " + loginResponse.user.getPassword() + "\n";
content += "Status: " + loginResponse.getStatus() + "\n";
content += "Description: " + loginResponse.getDescription() + "\n\n";
Log.i("Read me", content);
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.i("Error", t.getMessage());
}
});
}
private void createPost() {
User login = new User("New Name", "New Password");
Call<LoginResponse> call = jsonPlaceHolderApi.createPost(login);
call.enqueue(new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (!response.isSuccessful()) {
Log.i("Code: ", String.valueOf(response.code()));
return;
}
LoginResponse loginResponse = response.body();
String content = "";
content += "Code: " + response.code() + "\n";
content += "UserName: " + loginResponse.user.getUsername() + "\n";
content += "Password: " + loginResponse.user.getPassword() + "\n";
content += "Status: " + loginResponse.getStatus() + "\n";
content += "Description: " + loginResponse.getDescription() + "\n\n";
Log.i("Read me", content);
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.i("Failure", t.getMessage());
}
});
}
For the POST issue, 405 (Method Not Allowed), it seems like the "admin" action doesn't support the POST method.
I have been trying to get this over for a while now with little or no success. Right now, I am really out of options. I will appreciate some assistance or pointers towards the right direction.... since I believe I am not doing somethings very well.
After parsing with the code below, I have null values in most of the fields: Result{id=30c26c8a-8bdf-4d4d-8f8d-a19661f16877, name=Andriod_Office_Task, owner =generated.Owner#53d8d10a, comment=, creationTime=2016-09-09T19:30, modificationTime=2016-09-09T19:30:05+02:00, reportId=null, taskid=null, host=null, port=null, nvt=null, scanNVTVersion=null, threat=null, severity=null, description=null}
The parsing methods (other methods are excluded for brevity):
private List<Result> readDocument(XMLStreamReader parser) throws XMLStreamException, DatatypeConfigurationException {
List<Result> results = new ArrayList<>();
while (parser.hasNext()) {
int eventType = parser.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = parser.getLocalName();
if (elementName.equals("result"))
results.add(readResult(parser));
break;
case XMLStreamReader.END_ELEMENT:
return results;
}
}
throw new XMLStreamException("Premature end of file");
}
public Result readResult(XMLStreamReader parser) throws XMLStreamException, DatatypeConfigurationException {
Result result = new Result();
result.setId(parser.getAttributeValue(null, "id"));
Report report = new Report();
Task task = new Task();
while (parser.hasNext()) {
int eventType = parser.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = parser.getLocalName();
if (elementName.equals("name"))
result.setName(readCharacters(parser));
else if (elementName.equals("host"))
result.setHost(readCharacters(parser));
else if (elementName.equals("owner"))
result.setOwner(readOwner(parser));
else if (elementName.equals("comment"))
result.setComment(readCharacters(parser));
else if (elementName.equals("creation_time"))
result.setCreationTime(readCreationTime(parser));
else if (elementName.equals("modification_time"))
result.setModificationTime(readCharacters(parser));
else if (elementName.equals("report"))
report.setId(readReport(parser));
else if (elementName.equals("task"))
task.setId(readTask(parser));
else if (elementName.equals("user_tags"))
result.setUserTags(readUserTags(parser));
else if (elementName.equals("port"))
result.setPort(readCharacters(parser));
else if (elementName.equals("nvt"))
result.setNvt(readNvt(parser));
else if (elementName.equals("scan_nvt_version"))
result.setScanNVTVersion(readCharacters(parser));
else if (elementName.equals("threat"))
result.setThreat(readCharacters(parser));
else if (elementName.equals("severity"))
result.setSeverity(readCharacters(parser));
else if (elementName.equals("qod"))
result.setQod((Qod) readQod(parser));
else if (elementName.equals("description"))
result.setDescription(readCharacters(parser));
break;
case XMLStreamReader.END_ELEMENT:
}
return result;
}
throw new XMLStreamException("Premature end of file");
}
private String readCharacters(XMLStreamReader reader) throws XMLStreamException {
StringBuilder result = new StringBuilder();
while (reader.hasNext()) {
int eventType = reader.next();
switch (eventType) {
case XMLStreamReader.CHARACTERS:
result.append(reader.getText());
break;
case XMLStreamReader.END_ELEMENT:
return result.toString();
}
}
throw new XMLStreamException("Premature end of file");
}
}
The result class is below :
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Result {
#XmlAttribute
private String id;
#XmlElement
private String name;
#XmlElement
private Task task;
#XmlElement
private String comment;
#XmlElement(name = "creation_time")
String creationTime;
#XmlElement(name = "modification_time")
private String modificationTime;
// TODO user_tags
#XmlElement
private UserTags userTags;
#XmlElement
private Owner owner;
#XmlElement
private Qod qod;
/**
* // * The report the result belongs to (only when details were requested)
* //
*/
#XmlElementWrapper(name = "report")
#XmlElement(name = "reportId")
private String reportId;
#XmlElement
private String host;
#XmlElement
private String port;
#XmlElement
private NVT nvt;
#XmlElement(name = "scan_nvt_version")
private String scanNVTVersion;
#XmlElement
private String threat;
#XmlElement
private String severity;
#XmlElement
private String description;
public Result() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getCreationTime() {
return creationTime;
}
public void setCreationTime(String creationTime) {
this.creationTime = creationTime;
}
public String getModificationTime() {
return modificationTime;
}
public void setModificationTime(String modificationTime) {
this.modificationTime = modificationTime;
}
public UserTags getUserTags() {
return userTags;
}
public void setUserTags(UserTags userTags) {
this.userTags = userTags;
}
public Qod getQod() {
return qod;
}
public void setQod(Qod qod) {
this.qod = qod;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public String getReportId() {
return reportId;
}
public void setReportId(String reportId) {
this.reportId = reportId;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public NVT getNvt() {
return nvt;
}
public void setNvt(NVT nvt) {
this.nvt = nvt;
}
public String getScanNVTVersion() {
return scanNVTVersion;
}
public void setScanNVTVersion(String scanNVTVersion) {
this.scanNVTVersion = scanNVTVersion;
}
public String getThreat() {
return threat;
}
public void setThreat(String threat) {
this.threat = threat;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Result{" + "id=" + id +
", name=" + name + ", owner =" + owner +
", comment=" + comment + ", creationTime=" + creationTime + ", modificationTime=" + modificationTime
+ ", reportId=" + reportId + ", taskid=" + task + ", host=" + host + ", port=" + port + ", nvt=" + nvt
+ ", scanNVTVersion=" + scanNVTVersion + ", threat=" + threat + ", severity=" + severity
+ ", description=" + description + '}';
}
}
<get_results_response status="200" status_text="OK">
<result id="30c26c8a-8bdf-4d4d-8f8d-a19661f16877">
<name>Trace route</name>
<owner>
<name>admin</name>
</owner>
<comment/>
<creation_time>2016-09-09T19:30:05+02:00</creation_time>
<modification_time>2016-09-09T19:30:05+02:00</modification_time>
< id="2a6d7f75-f6b7-40b2-a792-b558fada375b"/>
<task id="e59ac66b-5b59-4756-bace-37bb1106276d">
<name>Andriod_Office_Task</name>
</task>
<user_tags>
<count>0</count>re
</user_tags>
<host>172.16.53.178</host>
<port>general/tcp</port>
<nvt oid="1.3.6.1.4.1.25623.1.0.51662">
<name>Traceroute</name>
<family>General</family>
<cvss_base>0.0</cvss_base>
<cve>NOCVE</cve>
<bid>NOBID</bid>
<xref>NOXREF</xref>
<tags>cvss_base_vector=AV:N/AC:L/Au:N/C:N/I:N/A:N|qod_type=remote_banner|solution=Block unwanted packets from escaping your network.|summary=A traceroute from the scanning server to the target system was
conducted. This traceroute is provided primarily for informational
value only. In the vast majority of cases, it does not represent a
vulnerability. However, if the displayed traceroute contains any
private addresses that should not have been publicly visible, then you
have an issue you need to correct.</tags>
<cert/>
</nvt>
<scan_nvt_version>$Revision: 2837 $</scan_nvt_version>
<threat>Log</threat>
<severity>0.0</severity>
<qod>
<value>80</value>
<type>remote_banner</type>
</qod>
<description>Here is the route from 192.168.14.128 to 172.16.53.178:
192.168.14.128
172.16.53.178</description>
</result>
<filters id="">
<term>first=1 rows=-1 sort=name</term>
<keywords>
<keyword>
<column>first</column>
<relation>=</relation>
<value>1</value>
</keyword>
<keyword>
<column>rows</column>
<relation>=</relation>
<value>-1</value>
</keyword>
<keyword>
<column>sort</column>
<relation>=</relation>
<value>name</value>
</keyword>
</keywords>
</filters>
<sort>
<field>name
<order>ascending</order></field>
</sort>
<results max="-1" start="1"/>
<result_count>3444
<filtered>1</filtered>
<page>1</page></result_count>
</get_results_response>
After some research and attempts with some common xml parsing approaches, I ended up using jackson-dataformat-xml approach. While this might not be the best it gave me what I wanted with much less code. Basically, I had to adapt the annotations in the model classes as below :
#JsonIgnoreProperties(ignoreUnknown=true)
#JacksonXmlRootElement(localName = "results")
public class Results {
#JacksonXmlProperty(localName = "result")
#JacksonXmlElementWrapper(useWrapping = false)
public Result [] result;
public Results() {
}
public Result[] getResult() {
return result;
}
public void setResult(Result[] result) {
this.result = result;
}
#Override
public String toString() {
return "Results [result=" + Arrays.toString(result) + "]";
}
And some adaptations for the parsing class:
public class GetReportsResponseHandler extends DefaultHandler<GetReportsResponse> {
private XmlMapper mapper = new XmlMapper();
public GetReportsResponseHandler() {
super(new GetReportsResponse(), "get_reports_response");
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary);
mapper.setAnnotationIntrospector(pair);
}
#Override
protected void parseStartElement(XMLStreamReader parser) throws XMLStreamException, IOException {
if ("report".equals(parser.getName().toString())){
Report report = mapper.readValue(parser, Report.class);
response.addReport(report);
}
I am trying to read an API link which contains data of JSON format. this is what i am trying to read and display on the phone:
[[],{"index":"2","name":"jim","email":"jim#outlook.com","contact":"0122511336","username":"jim","password":"jim","photo":"student.jpg","status":"Active"}]
The program supposed to authenticate the username and password inputs and this dipsplay the content of the above from URL.
Below is the codes and so far what I have done. Please someone help me to get this through.
package org.json.me;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class Login extends MIDlet implements CommandListener {
private String name;
private String email;
private int contact;
private String username;
private String password;
private String status;
private final String JSONformat = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email=email;
}
public int getContact() {
return contact;
}
public void setContact (int contact) {
this.contact=contact;
}
public String getUsername () {
return username;
}
public void setUsername (String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword (String Password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status=status;
}
public String toString() {
return getName()+""+getEmail()+""+getContact()+""+getUsername()+""+getPassword()+""+getStatus();
}
public String fromJSON(String jsonString) {
try {
JSONObject json = new JSONObject(jsonString);
setName(json.getString("name"));
setEmail(json.getString("email"));
setContact(json.getInt("contact"));
setUsername(json.getString("username"));
setPassword(json.getString("password"));
setStatus(json.getString("status"));
}
catch (JSONException e) {
e.printStackTrace();
}
return JSONformat;
}
TextField UserName = null;
TextField Password = null;
Form authForm, mainscreen;
TextBox t = null;
StringBuffer b = new StringBuffer();
private Display myDisplay = null;
private Command okCommand = new Command("OK", Command.OK, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 2);
private Command backCommand = new Command("Back", Command.BACK, 2);
private Alert alert = null;
public Login() {
myDisplay = Display.getDisplay(this);
UserName = new TextField("Username", "", 10, TextField.ANY);
Password = new TextField("Password", "", 10, TextField.ANY);
authForm = new Form("Identification");
mainscreen = new Form("Logging IN");
mainscreen.append("Logging in....");
mainscreen.addCommand(backCommand);
authForm.append(UserName);
authForm.append(Password);
authForm.addCommand(okCommand);
authForm.addCommand(exitCommand);
authForm.setCommandListener(this);
myDisplay.setCurrent(authForm);
}
public void startApp() throws MIDletStateChangeException {
}
public void pauseApp() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
public void commandAction(Command c, Displayable d) {
if ((c == okCommand) && (d == authForm)) {
if (UserName.getString().equals("") || Password.getString().equals("")) {
alert = new Alert("Error", "You should enter Username and Password", null,AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
myDisplay.setCurrent(alert);
}
else {
//myDisplay.setCurrent(mainscreen);
login(UserName.getString(), Password.getString());
}
}
if ((c == backCommand) && (d == mainscreen)) {
myDisplay.setCurrent(authForm);
}
if ((c == exitCommand) && (d == authForm)) {
notifyDestroyed();
}
}
public void login(String UserName, String PassWord) {
HttpConnection connection = null;
DataInputStream in = null;
String base = "http://sunday-tech.com/chunghua/api/login.php";
String url = base + "?username=" + UserName + "&password=" + PassWord;
OutputStream out = null;
try
{
connection = (HttpConnection) Connector.open(url);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("IF-Modified-Since", "2 Oct 2002 15:10:15 GMT");
connection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Length", "" + (UserName.length() + PassWord.length()));
connection.setRequestProperty("UserName", UserName);
connection.setRequestProperty("PassWord", PassWord);
out = connection.openDataOutputStream();
out.flush();
in = connection.openDataInputStream();
int ch;
while ((ch = in.read()) != -1) {
b.append((char) ch);
//System.out.println((char)ch);
}
mainscreen.append(fromJSON(b.toString()));
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (connection != null) {
connection.close();
}
}
catch (Exception x) {
}
myDisplay.setCurrent(mainscreen);
}
}
Change your setter methods to also change the TextField values. For example
public void setUsername (String username) {
this.username = username;
this.UserName.setString(username);
}
My string is like this:
[{"trends":[{"name":"#Happy16thPoniGoyangLimitedEditionJKT48","url":"http:\/\/twitter.com\/search?q=%23Happy16thPoniGoyangLimitedEditionJKT48","promoted_content":null,"query":"%23Happy16thPoniGoyangLimitedEditionJKT48","events":null},{"name":"#SemihVAROLTAYFAileHaftaSonuTakibi","url":"http:\/\/twitter.com\/search?q=%23SemihVAROLTAYFAileHaftaSonuTakibi","promoted_content":null,"query":"%23SemihVAROLTAYFAileHaftaSonuTakibi","events":null},{"name":"#JeeveTeriJodi","url":"http:\/\/twitter.com\/search?q=%23JeeveTeriJodi","promoted_content":null,"query":"%23JeeveTeriJodi","events":null},{"name":"#Tolga\u00D6\u011F\u00FCt\u0130leTakiple\u015Fme","url":"http:\/\/twitter.com\/search?q=%23Tolga%C3%96%C4%9F%C3%BCt%C4%B0leTakiple%C5%9Fme","promoted_content":null,"query":"%23Tolga%C3%96%C4%9F%C3%BCt%C4%B0leTakiple%C5%9Fme","events":null},{"name":"#CNEnjoyMondayyy","url":"http:\/\/twitter.com\/search?q=%23CNEnjoyMondayyy","promoted_content":null,"query":"%23CNEnjoyMondayyy","events":null},{"name":"Medha Patkar","url":"http:\/\/twitter.com\/search?q=%22Medha+Patkar%22","promoted_content":null,"query":"%22Medha+Patkar%22","events":null},{"name":"Asaram Bapuji","url":"http:\/\/twitter.com\/search?q=%22Asaram+Bapuji%22","promoted_content":null,"query":"%22Asaram+Bapuji%22","events":null},{"name":"Tune Talk","url":"http:\/\/twitter.com\/search?q=%22Tune+Talk%22","promoted_content":null,"query":"%22Tune+Talk%22","events":null},{"name":"Golden Globes 2014","url":"http:\/\/twitter.com\/search?q=%22Golden+Globes+2014%22","promoted_content":null,"query":"%22Golden+Globes+2014%22","events":null},{"name":"Game of Thrones Season 4","url":"http:\/\/twitter.com\/search?q=%22Game+of+Thrones+Season+4%22","promoted_content":null,"query":"%22Game+of+Thrones+Season+4%22","events":null}],"as_of":"2014-01-13T09:59:22Z","created_at":"2014-01-13T09:07:24Z","locations":[{"name":"Worldwide","woeid":1}]}]
I can parse this json string when I remove "[" and "]" from first and last character by following code:
private TrendTags getTrendTagsJSON(String jsonString) {
TrendTags trendTags = null;
jsonString = jsonString.substring(1, jsonString.length()-1);
try {
//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//convert json string to object
trendTags = objectMapper.readValue(jsonString, TrendTags.class);
System.out.println(trendTags);
} catch (JsonParseException e) {
System.out.println(e.getMessage());
} catch (JsonMappingException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
return trendTags;
}
And my TrendsTag class is this:
public class TrendTags {
#JsonProperty("trends")
private Trend[] trend;
#JsonProperty("locations")
private TrendLocation[] trendLocation;
#Override
public String toString() {
return "TrendTags{" +
"trend=" + Arrays.toString(trend) +
", trendLocation=" + Arrays.toString(trendLocation) +
'}';
}
public Trend[] getTrend() {
return trend;
}
public void setTrend(Trend[] trend) {
this.trend = trend;
}
public TrendLocation[] getTrendLocation() {
return trendLocation;
}
public void setTrendLocation(TrendLocation[] trendLocation) {
this.trendLocation = trendLocation;
}
/************************
* Trend item class *
************************/
public static class Trend {
private String name;
private String url;
private String query;
#Override
public String toString() {
return "Trend {" +
"name='" + name + '\'' +
", url='" + url + '\'' +
", query='" + query + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
}
/************************
* Trend location class *
************************/
public static class TrendLocation {
private String name;
private int woeid;
#Override
public String toString() {
return "TrendLocation{" +
"name='" + name + '\'' +
", woeid=" + woeid +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWoeid() {
return woeid;
}
public void setWoeid(int woeid) {
this.woeid = woeid;
}
}
}
Since I have one object in array so it's possible to remove "[" and "]" from first and last chatacter. But this is not the solution.
My question is how to parse the json string with "[" and "]" characters? There should be a simple solution but I cannot find it. Thanks
Your JSON represents an array of your TrendTags objects. You're attempting to parse it as if it represented a single TrendTags object.
Get rid of all that code trying to modify the JSON, and just do:
TrendTags[] trendTags =
objectMapper.readValue(jsonString, TrendTags[].class);
That said, using a List is generally better;
List<TrendTags> trendTags =
objectMapper.readValue(jsonString, new TypeReference<List<TrendTags>>(){});
I can get my data, because i get an error on line 66 which is. but error saying that I get a null value. although I've looked through the code, I think even that, it gets the right value in. I tried using a method that I made just for it. but after that it did not work, I used a method that works, which I use to log in with.
label_KontoId.setText(myPrivate.getAccountName());
My class's looks like this: In my main i got this code
public void SetId(String AccountId, String kode) {
AccountName = AccountId;
Password = kode;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PrivatekunderGUI frame = new PrivatekunderGUI();
frame.setVisible(true);
myPrivate = PR.LogindCheck(AccountName, Password);
} catch (Exception e) {
e.printStackTrace();
}
}
});
label_KontoId.setText(myPrivate.getAccountName());
}
This is not all the code, just what's necessary. The other code is generated for the GUI:
public class Private extends Customers {
private String AccountName;
private String Password;
private int Balance;
private int AccountId;
public Private(String Name, int Number, int Zip, String Address, int Phone,
int Balance, int AccountId, String AccountName, String Password) {
super(Name, Number, Zip, Address, Phone);
this.AccountId = AccountId;
this.Balance = Balance;
this.AccountName = AccountName;
this.Password = Password;
}
public String getAccountName() {
return AccountName;
}
public String getPassword() {
return Password;
}
public int getBalance() {
return Balance;
}
public int getAccountId() {
return AccountId;
}
public void setAccountName(String accountName) {
AccountName = accountName;
}
public void setPassword(String password) {
Password = password;
}
public void setBalance(int balance) {
Balance = balance;
}
public void setAccountId(int accountId) {
AccountId = accountId;
}
void account() {
}
#Override
public String toString() {
return "Private [AccountName=" + AccountName + ", Password=" + Password
+ ", Balance=" + Balance + ", AccountId=" + AccountId
+ ", getName()=" + getName() + ", getNumber()=" + getNumber()
+ ", getZip()=" + getZip() + ", getAddress()=" + getAddress()
+ ", getPhone()=" + getPhone() + "]";
}
}
and my PrivateRegistre looks like this:
public class PrivateRegistre {
private ArrayList<Private> privater = new ArrayList<>();
public PrivateRegistre() {
gem("Driton", 32233223, 2400, "Hallovej 54", 32233223, 543442, 1,
"Driton", "1234");
}
public void gem(String Name, int Number, int Zip, String Address,
int Phone, int Balance, int AccountId, String AccountName,
String Password) {
privater.add(new Private(Name, Number, Zip, Address, Phone, Balance,
AccountId, AccountName, Password));
}
public ArrayList<Private> hentalleprivatekunder() {
return privater;
}
public Private findkunde(int AccountId) {
for (Private privat : privater) {
if (privat.getAccountId() == AccountId) {
return privat;
}
}
return null;
}
public Private LogindCheck(String AccountName, String Password) {
for (Private privat : privater) {
if (privat.getAccountName().equals(AccountName)
&& privat.getPassword().equals(Password)) {
return privat;
}
}
return null;
}
public boolean sletprivatekunde(int AccountId) {
Private privat = findkunde(AccountId);
if (privat == null)
return false;
privater.remove(privat);
return true;
}
#Override
public String toString() {
return "PrivateRegistre [Private Kunder=" + privater + "]";
}
public Private HentLogindOplysninger(String AccountName) {
for (Private privat : privater) {
if (privat.getAccountName().equals(AccountName)) {
return privat;
}
}
return null;
}
}
Because you are returning null in your methods
findkunde(...)
HentLogindOplysninger(...)
LogindCheck(...)
You shouldn't be returning null - return something useful and if you have nothing to return better use void in method return type
myPrivate = PR.LogindCheck(AccountName, Password); here you are getting null beacuse you are returning null in method
public Private LogindCheck(String AccountName, String Password)
& also in
public Private findkunde(int AccountId)
just replacereturn null statement with something that would make sense and can be assigned and then used without resulting into NullPointerException;