I'm trying to parse the below given json.
{
"sections": [
{
"title": "Title android",
"level": 1,
"content": [
{
"type": "paragraph",
"text": "This is paragraph 1 for android."
}
{
"type": "paragraph",
"text": "This is paragraph 2 for android"
}
],
"images": [
{
"src": "http://image1 android.",
"caption": "Image 1."
},
{
"src": "http://image2 android",
"caption": "Image 2."
}
]
},
{
"title": "Title java",
"level": 2,
"content": [
{
"type": "paragraph",
"text": "This is paragraph 1 for Java."
},
{
"type": "paragraph",
"text": "This is paragraph 2 for Java"
}
],
"images": [
{
"src": "http://image1 java.",
"caption": "Image 1."
},
{
"src": "http://image2 java",
"caption": "Image 2."
}
]
},
{
"title": "Title json",
"level": 3,
"content": [
{
"type": "paragraph",
"text": "This is paragraph 1 for Json."
},
{
"type": "paragraph",
"text": "This is paragraph 2 for Json"
},
{
"type": "paragraph",
"text": "This is paragraph 3 for Json"
}
],
"images": [
{
"src": "http://image1 Json.",
"caption": "Image 1."
},
{
"src": "http://image2 Json",
"caption": "Image 2."
}
]
}
I want to output these Json as
Title 1 :Title android. \n
Content 1:This is paragraph 1 for android.
This is paragraph 2 for android.
Image 1:http:// image1 android.
Image 2:http:// image2 android.
Title :Title Java.
Content:This is paragraph 1 for Java.
This is paragraph 2 for Java.
Image 1:http:// image1 Java.
Image 2:http:// image2 Java.
... and so on.
What I have done so far
public class ParseJSON {
public static String[] titles;
public static String[] contents;
public static String[] levels;
public static final String JSON_ARRAY = "sections";
public static final String TITLE = "title";
public static final String CONTENT = "content";
public static final String TEXT = "text";
private JSONArray sections = null;
private JSONArray content = null;
private String json;
public ParseJSON(String json) {
this.json = json;
}
protected void parseJSON() {
JSONObject jsonObject ;
try {
jsonObject = new JSONObject(json);
sections = jsonObject.getJSONArray(JSON_ARRAY);
titles = new String[sections.length()];
levels = new String[sections.length()];
for (int i = 0; i < sections.length(); i++) {
titles[i] = sections.getJSONObject(i).getString(TITLE);
JSONArray content = sections.getJSONObject(i).getJSONArray(CONTENT);
contents = new String[content.length()];
Log.d("MainActivity",contents.toString());
for (int j = 0; j < content.length(); j++) {
contents[j] += content.getJSONObject(j).getString(TEXT).toString() + "\n\n";
//Log.d("MainActivity",contents.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The above code is not complete.
I want to print the json as above.
But I'm not getting the title part and paragraph part as needed.
When I parse the TEXT from content array it gives all the paragraphs combined from the json as content[0],content[1] and so on.
But I want contents with respect to titles only
I think the link part plays some role,but I don't know how.
UPDATE
What if I want the output as the middle one alone.ie,
//android title part //not needed
//The part needed is below one:
Title :Title Java.
Content:This is paragraph 1 for Java.
This is paragraph 2 for Java.
Image 1:http:// image1 Java.
Image 2:http:// image2 Java.
//json title part //not needed
Why do you torture yourself by manually parse JSON? May I recommend you to use some lightweight JSON Parser. This is how I do that in Android with org.codehaus.jackson mapper:
package yourpackage;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JsonMapper
{
private static ObjectMapper objectMapper = new ObjectMapper();
public static Object fromJsonToJavaObject(String jsonObject, Class<?> clazz) throws JsonParseException, JsonMappingException, IOException
{
return objectMapper.readValue(jsonObject, clazz);
}
public static String fromJavaObjectToJson(Object javaObject) throws JsonGenerationException, JsonMappingException, IOException
{
StringWriter stringWriter = new StringWriter();
objectMapper.writeValue(stringWriter, javaObject);
return stringWriter.toString();
}
public static List<?> fromJsonToJavaObjects(String jsonObject, Class<?> clazz) throws JsonParseException, JsonMappingException, IOException
{
return objectMapper.readValue(jsonObject, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
}
}
For your case, just pass the JSON string and the expected result type to the first method like TitleWithImages.class.
This would be the Maven dependency (but you are using Android studio):
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
try {
JSONObject jsonObject = new JSONObject(data);
sections = jsonObject.getJSONArray("sections");
for (int i = 0; i < sections.length(); i++) {
JSONObject contentJSON = sections.getJSONObject(i);
Log.d("", "Title: "+ contentJSON.getString("level") + " " + contentJSON.getString("title") );
JSONArray contentArray = contentJSON.getJSONArray("content");
Log.d("","Content: " + contentJSON.getString("level") + " " );
for (int j = 0; j < contentArray.length(); j++) {
Log.d("",contentArray.getJSONObject(i).getString("text"));
}
JSONArray imageArray = contentJSON.getJSONArray("images");
Log.d("","Images: " + contentJSON.getString("level") + " " );
for (int j = 0; j < imageArray.length(); j++) {
Log.d("",imageArray.getJSONObject(j).getString("src"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I have printed the output on Logcat you can just add it in string arrays or better create object with parameters you need
Using the json converter to pojo tool like this, you can generate Plain Old Java Objects (POJO) that you can use to easily manipulate your json results.
From your json string, I was able to generate the following Java classes:
public class Content {
#SerializedName("type")
#Expose
private String type;
#SerializedName("text")
#Expose
private String text;
/**
*
* #return
* The type
*/
public String getType() {
return type;
}
/**
*
* #param type
* The type
*/
public void setType(String type) {
this.type = type;
}
/**
*
* #return
* The text
*/
public String getText() {
return text;
}
/**
*
* #param text
* The text
*/
public void setText(String text) {
this.text = text;
}
}
Then this represents the Image entity:
public class Image {
#SerializedName("src")
#Expose
private String src;
#SerializedName("caption")
#Expose
private String caption;
/**
*
* #return
* The src
*/
public String getSrc() {
return src;
}
/**
*
* #param src
* The src
*/
public void setSrc(String src) {
this.src = src;
}
/**
*
* #return
* The caption
*/
public String getCaption() {
return caption;
}
/**
*
* #param caption
* The caption
*/
public void setCaption(String caption) {
this.caption = caption;
}
}
This is the umbrella that contains the two objects as lists:
public class Section {
#SerializedName("title")
#Expose
private String title;
#SerializedName("level")
#Expose
private int level;
#SerializedName("content")
#Expose
private List<Content> content = new ArrayList<Content>();
#SerializedName("images")
#Expose
private List<Image> images = new ArrayList<Image>();
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The level
*/
public int getLevel() {
return level;
}
/**
*
* #param level
* The level
*/
public void setLevel(int level) {
this.level = level;
}
/**
*
* #return
* The content
*/
public List<Content> getContent() {
return content;
}
/**
*
* #param content
* The content
*/
public void setContent(List<Content> content) {
this.content = content;
}
/**
*
* #return
* The images
*/
public List<Image> getImages() {
return images;
}
/**
*
* #param images
* The images
*/
public void setImages(List<Image> images) {
this.images = images;
}
}
After generating them and saving in your project like any other class, you can now use Gson to convert your json String into these objects with properties.
Since you get a List of Sections in your json response, what you can do is simple:
List<Section> sections = new Gson().fromJson(jsonString, Section.class);
Now you have a list of sections that you can loop through to obtain images and content. Content, remember, has a list of its own, just like images do. From that you should be able to easily get your data.
I hope this helps you.
You can use Gradle to add Gson or download the jar file and add to your /libs folder in android studio.
Related
I have a JSON which I created from SQL Server using JSON PATH, below is how it looks, this JSON is stored in a STRING type of variable.
{
"users": [
{
"displayName": "Dennis Law",
"givenName": "Dennis",
"surname": "Law",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "dennislaw#gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-IN",
"extension_tenant": "Team1"
},
{
"displayName": "Geroge West",
"givenName": "Geroge",
"surname": "West",
"extension_user_type": "user",
"identities": [
{
"signInType": "userName",
"issuerAssignedId": "gwest"
}
],
"extension_timezone": "PST",
"extension_locale": "en-GB",
"extension_tenant": "Team2"
},
{
"displayName": "Shaggy Nate",
"givenName": "Shaggy",
"surname": "Nate",
"extension_user_type": "user",
"identities": [
{
"signInType": "userName",
"issuerAssignedId": "Shaggynatealpha"
}
],
"extension_timezone": "NST",
"extension_locale": "en-AF",
"extension_tenant": "Team1"
}
]
}
In the below JSON, I have a key extension_tenant which is like a team, so we have values like Team1, Team2, Team3...and so on
I want to know if there is a way I can break this JSON based on extension_tenant and store it in STRING based on extension_tenant, so it will look like this.
Suppose all with extension_tenant = Team1 will be stored in a separate STRING,
example :
String Team1 = "
{
"users": [
{
"displayName": "Dennis Law",
"givenName": "Dennis",
"surname": "Law",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "dennislaw#gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-IN",
"extension_tenant": "Team1"
},
{
"displayName": "Shaggy Nate",
"givenName": "Shaggy",
"surname": "Nate",
"extension_user_type": "user",
"identities": [
{
"signInType": "userName",
"issuerAssignedId": "Shaggynatealpha"
}
],
"extension_timezone": "NST",
"extension_locale": "en-AF",
"extension_tenant": "Team1"
}
]
} ";
and for all with extension_tenant as Team2
String Team2 = "
{
"users": [
{
"displayName": "Geroge West",
"givenName": "Geroge",
"surname": "West",
"extension_user_type": "user",
"identities": [
{
"signInType": "userName",
"issuerAssignedId": "gwest"
}
],
"extension_timezone": "PST",
"extension_locale": "en-GB",
"extension_tenant": "Team2"
}
]
} ";
I hope I was able to explain what I am trying to do, please suggest and approach, I am active on stackoverflow, so i will probably reply and work on suggestions immediately. I am also looking for ways to do it mean while.
Check if following approach work for you
User.java
package json;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
#JsonProperty("displayName")
private String displayName;
#JsonProperty("givenName")
private String givenName;
#JsonProperty("surname")
private String surname;
#JsonProperty("extension_user_type")
private String extension_user_type;
#JsonProperty("identities")
private List<Identity> identities;
#JsonProperty("extension_timezone")
private String extension_timezone;
#JsonProperty("extension_locale")
private String extension_locale;
#JsonProperty("extension_tenant")
private String extension_tenant;
/**
* #return the displayName
*/
public String getDisplayName() {
return displayName;
}
/**
* #param displayName
* the displayName to set
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* #return the givenName
*/
public String getGivenName() {
return givenName;
}
/**
* #param givenName
* the givenName to set
*/
public void setGivenName(String givenName) {
this.givenName = givenName;
}
/**
* #return the surname
*/
public String getSurname() {
return surname;
}
/**
* #param surname
* the surname to set
*/
public void setSurname(String surname) {
this.surname = surname;
}
/**
* #return the extension_user_type
*/
public String getExtension_user_type() {
return extension_user_type;
}
/**
* #param extension_user_type
* the extension_user_type to set
*/
public void setExtension_user_type(String extension_user_type) {
this.extension_user_type = extension_user_type;
}
/**
* #return the identities
*/
public List<Identity> getIdentities() {
return identities;
}
/**
* #param identities
* the identities to set
*/
public void setIdentities(List<Identity> identities) {
this.identities = identities;
}
/**
* #return the extension_timezone
*/
public String getExtension_timezone() {
return extension_timezone;
}
/**
* #param extension_timezone
* the extension_timezone to set
*/
public void setExtension_timezone(String extension_timezone) {
this.extension_timezone = extension_timezone;
}
/**
* #return the extension_locale
*/
public String getExtension_locale() {
return extension_locale;
}
/**
* #param extension_locale
* the extension_locale to set
*/
public void setExtension_locale(String extension_locale) {
this.extension_locale = extension_locale;
}
/**
* #return the extension_tenant
*/
public String getExtension_tenant() {
return extension_tenant;
}
/**
* #param extension_tenant
* the extension_tenant to set
*/
public void setExtension_tenant(String extension_tenant) {
this.extension_tenant = extension_tenant;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('{');
stringBuilder.append("\"displayName\":" + "\"" + displayName + "\",");
stringBuilder.append("\"givenName\":" + "\"" + givenName + "\",");
stringBuilder.append("\"surname\":" + "\"" + surname + "\",");
stringBuilder.append("\"extension_user_type\":" + "\""
+ extension_user_type + "\",");
if (identities != null && identities.size() > 0) {
stringBuilder.append("\"identities\": [");
for (Identity identity : identities) {
stringBuilder.append(identity);
}
stringBuilder.append("],");
}
stringBuilder.append("\"extension_timezone\":" + "\""
+ extension_timezone + "\",");
stringBuilder.append("\"extension_locale\":" + "\"" + extension_locale
+ "\",");
stringBuilder.append("\"extension_tenant\":" + "\"" + extension_tenant
+ "\"");
stringBuilder.append('}');
return stringBuilder.toString();
}
}
Identity.java
package json;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Identity {
#JsonProperty("signInType")
private String signInType;
#JsonProperty("issuerAssignedId")
private String issuerAssignedId;
/**
* #return the signInType
*/
public String getSignInType() {
return signInType;
}
/**
* #param signInType
* the signInType to set
*/
public void setSignInType(String signInType) {
this.signInType = signInType;
}
/**
* #return the issuerAssignedId
*/
public String getIssuerAssignedId() {
return issuerAssignedId;
}
/**
* #param issuerAssignedId
* the issuerAssignedId to set
*/
public void setIssuerAssignedId(String issuerAssignedId) {
this.issuerAssignedId = issuerAssignedId;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('{');
stringBuilder.append("\"signInType\":" + "\"" + signInType + "\",");
stringBuilder.append("\"issuerAssignedId\":" + "\"" + issuerAssignedId
+ "\"");
stringBuilder.append('}');
return stringBuilder.toString();
}
}
Users.java
package json;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Users {
#JsonProperty("users")
List<User> users;
/**
* #return the users
*/
public List<User> getUsers() {
return users;
}
/**
* #param users
* the users to set
*/
public void setUsers(List<User> users) {
this.users = users;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('{');
if (users != null && users.size() > 0) {
stringBuilder.append("\"users\": [");
for (User user : users) {
stringBuilder.append(user);
}
stringBuilder.append("]");
}
stringBuilder.append('}');
return stringBuilder.toString();
}
}
Stored the json into d:/test.json
Post deserialization doing group by on extension_tenant attribute.
Converter.java
package json;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Converter {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
InputStream inputStream = null;
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
Users users = null;
try {
inputStream = new FileInputStream("d:/testsep.json");
//Get Users object
users = mapper.readValue(inputStream, Users.class);
StringBuilder stringBuilder = new StringBuilder();
Map<String, String> groupByTenantmap = null;
if (users != null) {
//retrieve list of User object
List<User> userList = users.getUsers();
if (userList != null && userList.size() > 0) {
groupByTenantmap = new HashMap<String, String>(
userList.size());
String extension_tenant = null;
String value = null;
for (User user : userList) {
//populate map group by extension_tenant
extension_tenant = user.getExtension_tenant();
if (groupByTenantmap.containsKey(extension_tenant)) {
value = groupByTenantmap.get(extension_tenant);
stringBuilder.append(value).append(',')
.append(user.toString());
groupByTenantmap.put(extension_tenant,
stringBuilder.toString());
} else {
groupByTenantmap.put(extension_tenant,
user.toString());
}
stringBuilder.setLength(0);
}
//iterate through map and create desired json structure
for (Entry<String, String> entry : groupByTenantmap
.entrySet()) {
stringBuilder.setLength(0);
stringBuilder.append("{").append("\"users\":")
.append("[");
stringBuilder.append(entry.getValue()).append("]");
stringBuilder.append("}");
System.out.println("String " + entry.getKey() + "=\""
+ stringBuilder.toString() + "\";");
System.out.println();
}
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Output:
String Team2="{"users":[{"displayName":"Geroge West","givenName":"Geroge","surname":"West","extension_user_type":"user","identities": [{"signInType":"userName","issuerAssignedId":"gwest"}],"extension_timezone":"PST","extension_locale":"en-GB","extension_tenant":"Team2"}]}";
String Team1="{"users":[{"displayName":"Dennis Law","givenName":"Dennis","surname":"Law","extension_user_type":"user","identities": [{"signInType":"emailAddress","issuerAssignedId":"dennislaw#gmail.com"}],"extension_timezone":"VET","extension_locale":"en-IN","extension_tenant":"Team1"},{"displayName":"Shaggy Nate","givenName":"Shaggy","surname":"Nate","extension_user_type":"user","identities": [{"signInType":"userName","issuerAssignedId":"Shaggynatealpha"}],"extension_timezone":"NST","extension_locale":"en-AF","extension_tenant":"Team1"}]}";
I want to parse json from json object and put it on textview. I tried some method but failed. The error:
expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
API SERVICE: Full ver http://139.255.86.189:83/service/api/checklistpertanyaan/1
{
"success": true,
"data": [
{
"idRchecklistpompa": "1",
"nmChecklist": "Membersihkan Body Pompa"
},
{
"idRchecklistpompa": "2",
"nmChecklist": "Membersihkan Kabel Tray Pompa"
},
Harian.java
public class Harian {
#SerializedName("idRchecklistpompa")
#Expose
private String idRchecklistpompa;
#SerializedName("nmChecklist")
#Expose
private String nmChecklist;
public String getIdRchecklistpompa() {
return idRchecklistpompa;
}
public String getNmChecklist() {
return nmChecklist;
}
public void setIdRchecklistpompa(String idRchecklistpompa) {
this.idRchecklistpompa = idRchecklistpompa;
}
public void setNmChecklist(String nmChecklist) {
this.nmChecklist = nmChecklist;
}
}
MainActivity.java
public class HarianActivity extends AppCompatActivity {
private TextView textViewResult;
/*private static String url = "http://139.255.86.189:83/service/api/checklistpertanyaan/1";*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_harian);
textViewResult = findViewById(R.id.text_view_result);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://139.255.86.189:83/service/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
HarianApi harianApi = retrofit.create(HarianApi.class);
Call<List<Harian>> call = harianApi.getHarian();
call.enqueue(new Callback<List<Harian>>() {
#Override
public void onResponse(Call<List<Harian>> call, Response<List<Harian>> response) {
if (!response.isSuccessful()) {
textViewResult.setText("CodeL " + response.code());
return;
}
List<Harian> harians = response.body();
for (Harian harian : harians) {
String content = "";
content += "ID " + harian.getIdRchecklistpompa() + "\n";
content += "NAMA " + harian.getNmChecklist() + "\n";
textViewResult.append(content);
}
}
#Override
public void onFailure(Call<List<Harian>> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
}
I would expect JSON that encapsulated a List of Harians to look like this:
[
{
"idRchecklistpompa": "1",
"nmChecklist": "Membersihkan Body Pompa"
},
{
"idRchecklistpompa": "2",
"nmChecklist": "Membersihkan Kabel Tray Pompa"
}
]
Instead, yours begins with:
{
"success": true,
"data": [
...
So it isn't correct for your API to return List<Harian>. Instead, your API should return a different class which looks more like:
public class Container {
#SerializedName("success")
private boolean success;
#SerializedName("data")
List<Harian> data;
public static class Harian {
#SerializedName("idRchecklistpompa")
#Expose
private String idRchecklistpompa;
#SerializedName("nmChecklist")
#Expose
private String nmChecklist;
public String getIdRchecklistpompa() {
return idRchecklistpompa;
}
public String getNmChecklist() {
return nmChecklist;
}
public void setIdRchecklistpompa(String idRchecklistpompa) {
this.idRchecklistpompa = idRchecklistpompa;
}
public void setNmChecklist(String nmChecklist) {
this.nmChecklist = nmChecklist;
}
}
}
And have your Retrofit API return Container rather than List<Harian>
Not sure if I understand but, to debug the problem what I would do is:
1.- Check as a String that response is a well formed JSON String.
Log.d(TAG, "My JSON String: " + response.code());
1.5.- Check if that string is a JSONObject or a JSONArray
2.- Probably try to create a JSONObject/JSONArray from that String to see if it triggers an exception.
try {
JSONObject jsonObject = new JSONObject(response.code());
} catch (JSONException e) {
e.printStackTrace();
}
3.- Try to parse the JSONObject but checking for exceptions:
try {
String nmChecklist = jsonObject.getString("nmChecklist");
} catch (JSONException e) {
e.printStackTrace();
}
4.- If you want to avoid exceptions since some objects may or may not have a key or value:
String nmChecklist = jsonObject.has("nmChecklist") && !jsonObject.isNull("nmChecklist") ? jsonObject.getString("nmChecklist") : null;
I hope this helps.
I think there is some problem with your class. The response is different from your pojo class. See json to pojo and create your Model as per the generated pojo.
First, sorry for possible duplicate. I found some questions regarding to similar problems. However, I still can't figure out what's wrong in my specific case.
So, example json from server:
[
{
"_id": "55f9690f30ef6f210e2dc3a5",
"ID": "74c4bf82-9f78-4df5-b9d7-6547e2a55eaa",
"Name": "myLand, Saarbrücken",
"__v": 0,
"Shops": [
{
"ID": "b8eacee1-b2c6-48aa-ac6f-2e7fbe3a5d68",
"Name": "ARA",
"_id": "55f9690f30ef6f210e2dc3a6",
"News": [
{
"ID": "d79b7f51-7d5c-4bd6-9321-e40c6e93788c",
"ValidFrom": "2015-01-08T00:00:00",
"ValidTo": "2015-09-30T00:00:00",
"_id": "55f9690f30ef6f210e2dc3a7",
"Texts": [
{
"ID": "TITLE",
"Value": "11. Wochenspiegel Firmenlauf",
"_id": "55f9690f30ef6f210e2dc3a9"
},
{
"ID": "BODY",
"Value": "Wir gratulieren zur ersten und gleich sehr erfolgreichen Teilnahme am 11.Wochenspiegel Firmenlauf in Dillingen,\r\nunsere Teams vom “Outlet center Wadgassen“ haben ihren Lauf mit tollen Zeiten abgeschlossen und hatten trotz\r\nhohen Temperaturen einen wunderbaren Tag – wie man sehen kann. Wir freuen uns schon jetzt auf nächstes Jahr!",
"_id": "55f9690f30ef6f210e2dc3a8"
}
]
}
],
"Texts": [
{
"ID": "DESCRIPTION",
"Value": "Mit Tradition in die Zukunft Seit sechs Jahrzehnten steht ara für vielfältige Schuhmode erstklassiger Qualität,",
"_id": "55f9690f30ef6f210e2dc3aa"
}
]
}
]
}
]
I generated class called Mall (and all subclasses for the rest of data structure):
public class Mall
{
private String Id;
private String ID;
private String Name;
private int V;
private List<Shop> Shops = new ArrayList<Shop>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* #return The Id
*/
public String getId()
{
return Id;
}
/**
* #param Id The _id
*/
public void setId(String Id)
{
this.Id = Id;
}
/**
* #return The ID
*/
public String getID()
{
return ID;
}
/**
* #param ID The ID
*/
public void setID(String ID)
{
this.ID = ID;
}
/**
* #return The Name
*/
public String getName()
{
return Name;
}
/**
* #param Name The Name
*/
public void setName(String Name)
{
this.Name = Name;
}
/**
* #return The V
*/
public int getV()
{
return V;
}
/**
* #param V The __v
*/
public void setV(int V)
{
this.V = V;
}
/**
* #return The Shops
*/
public List<Shop> getShops()
{
return Shops;
}
/**
* #param Shops The Shops
*/
public void setShops(List<Shop> Shops)
{
this.Shops = Shops;
}
public Map<String, Object> getAdditionalProperties()
{
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value)
{
this.additionalProperties.put(name, value);
}
}
Server returns conent-type text/plain. To modify content type, I wrote simple extend class:
public class RestTemplateJSON extends RestTemplate
{
#Override
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor) throws RestClientException
{
//logger.info(RestTemplateJSON.class.getSuperclass().getSimpleName() + ".doExecute() is overridden");
Assert.notNull(url, "'url' must not be null");
Assert.notNull(method, "'method' must not be null");
ClientHttpResponse response = null;
try
{
ClientHttpRequest request = createRequest(url, method);
if (requestCallback != null)
{
requestCallback.doWithRequest(request);
}
response = request.execute();
// Set ContentType to JSON
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
if (!getErrorHandler().hasError(response))
{
logResponseStatus(method, url, response);
} else
{
handleResponseError(method, url, response);
}
if (responseExtractor != null)
{
return responseExtractor.extractData(response);
} else
{
return null;
}
}
catch (IOException ex)
{
throw new ResourceAccessException("I/O error on " + method.name() +
" request for \"" + url + "\":" + ex.getMessage(), ex);
}
finally
{
if (response != null)
{
response.close();
}
}
}
private void logResponseStatus(HttpMethod method, URI url, ClientHttpResponse response)
{
//if (logger.isDebugEnabled())
{
try
{
System.out.println(method.name() + " request for \"" + url + "\" resulted in " +
response.getRawStatusCode() + " (" + response.getStatusText() + ")");
}
catch (IOException e)
{
// ignore
}
}
}
private void handleResponseError(HttpMethod method, URI url, ClientHttpResponse response) throws IOException
{
getErrorHandler().handleError(response);
}
}
Finally, this is how I'm trying to consume my webservice:
RestTemplateJSON restTemplate = new RestTemplateJSON();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Mall mall = restTemplate.getForObject(url, Mall.class);
However, I'm still getting the same exception:
Could not extract response: no suitable HttpMessageConverter found for
response type [m.m.restspringtest.Mall.Mall] and content type
[application/json]
As far as I know, if I change content type, it should be ok. Can you please tell me what am I doing wrong?
So, I finally figured it out. There is array in json, so I want to map it to Mall[], not Mall. I provided wrong class, there should be:
RestTemplateJSON restTemplate = new RestTemplateJSON();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Mall[] malls = restTemplate.getForObject(url, Mall[].class);
In a desktop software, the user is available to presh a button and refresh the "database".
All the info is provided by an online service which returns JSON responses, those responses are saved into DAT files and then parsed with http://www.json.org/java/index.html in order to be saved into in-memory variables as String. The DAT files are only for break-exception-support.
Ok, so I'd created a SwingWorker class which should:
parse the content from the in-memory variable
iterate through elements
recover items
update a progress bar
This is an example of the JSON code:
{
"key":"value",
"data":{
"Name1":{...},
"Name2":{...},
[...]
}
}
The full iteration of the "data" element will create a List, which I must use to create a JTable and populate the main frame of the GUI. But when executing the SwingWorker, it only returns a List which all elements are the last item of the JSON.
Here's the code the SwingWorker:
package com.wolfchamane.lolapi;
import com.wolfchamane.logging.LoCLogger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import org.json.JSONArray;
import org.json.JSONObject;
public class LoLChampions extends SwingWorker{
private static List<LoLChampion> _list;
private static JProgressBar _status;
private static LoCLogger _log;
private static String _exePath;
private static String _version;
private static LoLDDBB _ddbb;
//private static int _max;
public List<LoLChampion> getDataTable(){
return _list;
}
public LoLChampions(){}
public LoLChampions(JProgressBar status){
this();
_status = status;
}
public LoLChampions(JProgressBar status, LoCLogger log){
this(status);
_log = log;
}
public LoLChampions(JProgressBar status, LoCLogger log, String path){
this(status, log);
_exePath = path;
}
public LoLChampions(JProgressBar status, LoCLogger log, String path, LoLDDBB ddbb){
this(status, log, path);
_ddbb = ddbb;
}
public LoLChampions(JProgressBar status, LoCLogger log, String path, LoLDDBB ddbb, String version) throws Exception{
this(status, log, path, ddbb);
_version = version;
}
#Override
protected Object doInBackground() throws Exception {
getChampionsInfo(_ddbb.getJSONChampions());
return true;
}
public void getChampionsInfo(JSONObject jsonChampions) throws Exception{
String fldrImgsPath = _exePath+File.separator+"images";
String fldrImgsChampions = fldrImgsPath+File.separator+"champions";
File fldrImages = new File(fldrImgsPath);
if (fldrImages.isDirectory() || fldrImages.mkdir()){
File fldrChampions = new File(fldrImgsChampions);
if (fldrChampions.isDirectory() || fldrChampions.mkdir()){
JSONObject data = jsonChampions.getJSONObject("data");
JSONArray championsNames = data.names();
int _max = championsNames.length();
_status.setMaximum(_max);
if (_list == null)
_list = new ArrayList<LoLChampion>();
int curr = _list.size();
for (int i = 0; i < _max; i++){
_status.setString("Fetching ["+(curr+1)+"/"+_max+"] champions icos");
//Champion object
LoLChampion champion = new LoLChampion();
//Champion name
String name = String.valueOf(championsNames.get(i));
champion.setChampionName(name);
//Champion data
JSONObject jsonChamp = data.getJSONObject(name);
//Champion roles
JSONArray tags = jsonChamp.getJSONArray("tags");
//Main role
String mRole = String.valueOf(tags.get(0));
champion.setChampionMainRole(mRole);
//Secondary role (if exists)
String sRole = "";
if (tags.length() > 1)
sRole = String.valueOf(tags.get(1));
champion.setChampionSecondRole(sRole);
//Champion ico.
File pf = new File(fldrChampions.getPath()+File.separator+name+".jpg");
saveChampionImage(name, pf);
champion.setChampionIco(pf);
//Push LoLChampion object to list
_list.add(champion);
//Update status bar
curr = _list.size();
_status.setValue(curr);
System.gc();
}//for:i
_ddbb.setChampionsList(_list);
}else{
_log.error("Couldn't access or create \""+fldrImgsChampions+"\" folder");
throw new Exception("Couldn't access or create \""+fldrImgsChampions+"\" folder");
}//fi
}else{
_log.error("Couldn't access or create \""+fldrImgsPath+"\" folder");
throw new Exception("Couldn't access or create \""+fldrImgsPath+"\" folder");
}//fi
}
private void saveChampionImage(String name, File pf) throws Exception{
String endPointURL = (new ApiURLs()).getChampionsIcoURL();
endPointURL = endPointURL.replace("{version}", _version);
endPointURL = endPointURL.replace("{champion}", name);
try{
if (!pf.canWrite())
pf.createNewFile();
URL url = new URL(endPointURL);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(pf);
_log.info("Getting \""+endPointURL+"\"");
_log.info("Saving to \""+pf.getPath()+"\"");
byte[] buffer = new byte[2048];
int length;
while((length = is.read(buffer)) != -1){
os.write(buffer, 0, length);
}//while
is.close();
os.close();
}catch(Exception ex){
_log.error(ex.getMessage());
}
}
}
UPDATE
This is the complete JSON I want to parse:
https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?champData=tags&api_key=d34be821-7f22-4d55-85da-7409413e6379
I dont think your JSON example is well formed. JSON consists of name value pairs. There should be a ":" in between the name and a value.
Something like this:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
The JSON example you have provided looks malformed. Refer to json.org for more details
As the title suggested, how do I output a JSON array correctly in a table from a JSP page?
Right now whenever I display the JSON array object using <c:out value="${jsonArray}"/> but it just displays the whole contents of it in JSON string i.e {name: hello, address: baker street } but what I want to do is somehow parse this and display the info appropriately like this:
**name** **address**
hello baker street
spring java
tim sun
Is it possible in JSTL? I am new to JSTL stuff.
package com.kc.models;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import org.hibernate.Hibernate;
public class FileObject {
private String filename;
private String type;
private double size;
private Blob file;
private int id;
private String os;
private String description;
public FileObject() {
}
/**
* Constructor for use in returning just the list of files without the
* actual content
*
* #param name
* #param size
* #param id
* #param type
*/
public FileObject(String name, double size, int id, String type) {
this.filename = name;
this.type = type;
this.size = size;
this.id = id;
}
/**
* Constructor used to create a fileObject with all its properties assigned
*
* #param name
* #param size
* #param id
* #param type
* #param file
*/
public FileObject(String name, double size, int id, String type, Blob file,
String os, String description) {
this.filename = name;
this.type = type;
this.size = size;
this.id = id;
this.file = file;
this.os = os;
this.description = description;
}
public FileObject(String description){
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFilename() {
return filename;
}
public void setFilename(String fileName) {
this.filename = fileName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
public Blob getFile() {
return file;
}
public void setFile(Blob file) {
this.file = file;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
#Override
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO call a method that returns a list of Mobile Apps.
String fileType = ServletRequestUtils.getRequiredStringParameter(request, "fileType");
//testAddingSomeFilesToDb();
return new ModelAndView("" + "testJsonResponse", "jsonArray",
getFileList(fileType) );
}
/**
* Get file list from sql server based on type
* #return file list in json
*/
private JSONArray getFileList(String type) {
// TODO: Get request parameter that states what type of file extensions
// the client wants to recieve
ctx = new ClassPathXmlApplicationContext("zang-file-service.xml");
FileHelper file = (FileHelper) ctx.getBean("fileHelper");
return file.getFileList(type);
}
public JSONArray getFileList(String type) {
return constructJsonArray(dbFileHelper.getFileList(type));
}
private JSONArray constructJsonArray(List<FileObject> fileList) {
JSONArray mJsonArray = new JSONArray();
JSONObject mJsonFileObject = new JSONObject();
for (int i = 0; i < fileList.size(); i++) {
mJsonFileObject.put("FileObject", fileList.get(i));
System.out.println("File ID = " + fileList.get(i).getId());
System.out.println("fileName = " + fileList.get(i).getFilename());
System.out.println("type = " + fileList.get(i).getType());
System.out.println("size = " + fileList.get(i).getSize());
mJsonArray.add(mJsonFileObject);
}
return mJsonArray;
}
here is my jsp page:
<%# include file="/WEB-INF/jsp/include.jsp" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var files = "${jsonArray}";
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$(files).each(function(i, file) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(file.filename))
.append($('<td/>').text(file.id))
.append($('<td/>').text(file.type))
.append($('<td/>').text(file.size))
.append($('<td/>').text(file.os));
});
});
</script>
</head>
<body>
<div id="somediv"></div>
</body>
</html>
edit: here is my json output:
var files = [{"FileObject":{"description":"","file":null,"filename":"ACG Simulator(firefox).jpg","id":6,"os":"","size":172,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"car.jpg","id":11,"os":"","size":152,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts highlighted.jpg","id":13,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts highlighted2.jpg","id":14,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"contacts options.jpg","id":15,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"edit contact view.jpg","id":17,"os":"","size":52,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"fileObject.jpg","id":20,"os":"","size":30,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"groups.jpg","id":27,"os":"","size":31,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"inside contacts.jpg","id":31,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Music highlighted.jpg","id":37,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music options view.jpg","id":38,"os":"","size":46,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music phone view.jpg","id":39,"os":"","size":51,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"music vault view.jpg","id":40,"os":"","size":48,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"nice.jpg","id":41,"os":"","size":225,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo highlighted.jpg","id":42,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo options view.jpg","id":43,"os":"","size":48,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photo preview view.jpg","id":44,"os":"","size":46,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photos phone view.jpg","id":45,"os":"","size":51,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"photos vault view.jpg","id":46,"os":"","size":49,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"svn error.jpg","id":54,"os":"","size":35,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Video Highlighted.jpg","id":55,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"Videos options view.jpg","id":56,"os":"","size":47,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"videos phone view.jpg","id":57,"os":"","size":50,"type":"jpg"}},{"FileObject":{"description":"","file":null,"filename":"videos Vault view.jpg","id":58,"os":"","size":49,"type":"jpg"}}]
Your question is too ambigious to give a suitable answer, so I'll cover all possible scenarios:
You have it as a JavaScript variable like so:
var persons = [
{ "name": "John Doe", "address": "Main Street 1" },
{ "name": "Jane Doe", "address": "Baker Street 1" },
{ "name": "Jack Doe", "address": "Church Street 1" }
];
I'd suggest to use jQuery to create a HTML table out of it. Here's an SSCCE, you can copy'n'paste'n'run it:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var persons = [
{ "name": "John Doe", "address": "Main Street 1" },
{ "name": "Jane Doe", "address": "Baker Street 1" },
{ "name": "Jack Doe", "address": "Church Street 1" }
];
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$(persons).each(function(i, person) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(person.name))
.append($('<td/>').text(person.address));
});
});
</script>
</head>
<body>
<div id="somediv"></div>
</body>
</html>
You have it as a Java String variable like so:
String jsonPersons = "["
+ "{ \"name\": \"John Doe\", \"address\": \"Main Street 1\" },"
+ "{ \"name\": \"Jane Doe\", \"address\": \"Baker Street 1\" },"
+ "{ \"name\": \"Jack Doe\", \"address\": \"Church Street 1\" }"
+ "]";
Then I suggest to use a JSON parser to get a List<Person> out of it, like Google Gson:
List<Person> persons = new Gson().fromJson(jsonPersons, new TypeToken<List<Person>>() {}.getType());
Where the Person class look like this:
public class Person {
private String name;
private String address;
// Add or generate getters/setters.
}
Let the servlet put it in the request scope and forward to JSP for display like so:
request.setAttribute("persons", persons);
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);
In JSP, use JSTL <c:forEach> to iterate over it:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${persons}" var="person">
<tr>
<td>${person.name}</td>
<td>${person.address}</td>
</tr>
</c:forEach>
</table>
Same as 2), you have it as a Java variable, but you'd like to obtain it by Ajax in JSP. Then create a Servlet class which does the following in doGet() method:
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().write(jsonPersons);
And call it by jQuery Ajax with a callback which does the same as 1).
$(document).ready(function() {
var table = $('<table/>').appendTo($('#somediv'));
$.getJSON('url/to/servlet', function(persons) {
persons.each(function(i, person) {
$('<tr/>').appendTo(table)
.append($('<td/>').text(person.name))
.append($('<td/>').text(person.address));
});
});
});
Assuming:
jsonArray = [ {name: 'hello', address: 'baker street'}, ... ];
One way to do it is to construct the html in Javascript code like this:
var myHTMLStr = '<table>';
for(var i in jsonArray) {
myHTMLStr+='<tr><td>' + jsonArray[i]['name'] + '</td><td>' + jsonArray[i]['address'] + '</td></tr>';
}
myHTMLStr+='</table>';
Now display the HTML string:
document.getElementById('tableOutput').innerHTML = myHTMLStr;