return sms to persian language in Java - java

Im using API for sending SMS of product query and taking variable from properties file in java.
I need to convert the output message to utf-8 as i need to send SMS of Persian language, please help me.
here is the code:
List<String> returnMessage = new ArrayList<String>();
Properties messagePack = new Properties();
messagePack.load(RoshanSendSMS.class.getClassLoader().getResourceAsStream(String.format("%spack.properties", language)));
JSONObject parentObject = new JSONObject(result);
JSONArray objArray = (JSONArray) parentObject.get("PurchasedOfferArray");
int size = objArray.length();
for (int i = 0; i < size; i++) {
JSONObject obj = (JSONObject) objArray.get(i);
if (!obj.has("CatalogItemId")) {
continue;
}
String catalogId = obj.get("CatalogItemId").toString();
String productId = messagePack.getProperty(catalogId);
if (productId == null) {
continue;
}
String newProductId = "ProductName" + productId.split("t")[1];
String msg = messagePack.getProperty(newProductId);
if (msg == null) {
continue;
}
if (!returnMessage.contains(msg)) {
returnMessage.add(msg);
}
}
if(returnMessage.size()>0){
returnMessage.add(0, messagePack.getProperty("PRE_MSG"));
String fullMsg = String.join(" ", returnMessage);
System.out.println("Message: "+ fullMsg);
}else{
System.out.println("No message found");
}
return "SUCCESS";

Related

How to convert jsonstring to jsonobject in android?

i tried to convert jsonstring to json object. but its convert only first element.
here is my code
String d = [{"name":"kd","isMe":"yes","time":"10:12 AM"},{"name":"you","isMe":"no","time":"10:12 AM"}]
JSONObject j = new JSONObject(d);
its give following output
{"name":"kd","isMe":"yes","time":"10:12 AM"}
how can i convert this string into JSNOObject?
You can try like this, and your root is Json array not jsonobject
try {
JSONArray jsonArray = new JSONArray(d);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if(jsonObject == null) {
continue;
}
String name = jsonObject.optString("name");
String isMe = jsonObject.optString("isMe");
String time = jsonObject.optString("time");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Use this
JSONObject jsonObject = new JSONObject(my_json_string);
JSONArray jresult = jsonObject.getJSONArray("array_in_the_json_string");

JSON Object Android placing issue

I am trying to place this JSON Object in my Listview in android but I am having a problem with json mismatch.
This is the output of my server JSON :
{"Patient 0":
{"firstName":"admir","lastName":"andrade","email":"admirmonteiro#live.com"},
"Patient 1":
{"firstName":"alden","lastName":"andrade","email":"admirmonteiro#yahoo.com"}}
In my android code, I have the following code :
JSONObject object = new JSONObject(result);
How can I updated my list with both patients information without having to call each object once(if there are many, I don't know how to do this)? What do I need to do further to update my listView with two columns, one for first name and last name and the other with the email, as the JSON output form the server show? Is there a better way to do this?
This works fine,
JSONObject jObject = new JSONObject(result.trim());
Iterator<?> keys = jObject.keys();
while(keys.hasNext() ) {
String key = (String)keys.next();
if (jObject.get(key) instanceof JSONObject ) {
String firstName = ((JSONObject) jObject.get(key)).getString("firstName");
String lastName = ((JSONObject) jObject.get(key)).getString("lastName");
String email = ((JSONObject) jObject.get(key)).getString("email");
Log.d("jsondata","Firstname = "+firstName+"\nlastname = "+lastName+"\nemail = "+email);
}
}
Update
Here is the full codes that I tested,
String result = "{\"Patient 0\":{\"firstName\":\"admir\",\"lastName\":\"andrade\",\"email\":\"admirmonteiro#live.com\"},\"Patient 1\":{\"firstName\":\"alden\",\"lastName\":\"andrade\",\"email\":\"admirmonteiro#yahoo.com\"}}";
JSONObject jObject = null;
try {
jObject = new JSONObject(result.trim());
Iterator<?> keys = jObject.keys();
while(keys.hasNext() ) {
String key = (String)keys.next();
if (jObject.get(key) instanceof JSONObject ) {
String firstName = ((JSONObject) jObject.get(key)).getString("firstName");
String lastName = ((JSONObject) jObject.get(key)).getString("lastName");
String email = ((JSONObject) jObject.get(key)).getString("email");
Log.d("jsondata","Firstname = "+firstName+"\nlastname = "+lastName+"\nemail = "+email);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You can try this..
String result ="{\"Patient 0\":\n" +
"{\"firstName\":\"admir\",\"lastName\":\"andrade\",\"email\":\"admirmonteiro#live.com\"},\n" +
" \"Patient 1\":\n" +
"{\"firstName\":\"alden\",\"lastName\":\"andrade\",\"email\":\"admirmonteiro#yahoo.com\"}}";
JSONObject data = null;
try {
data = new JSONObject(""+result);
} catch (JSONException e) {
e.printStackTrace();
}
List<String> FName = new ArrayList<String>();
for(int i=0 ; i<data.length();i++){
try {
JSONObject innerData = data.getJSONObject("Patient "+i);
FName .add(innerData.getString("firstName"));
} catch (JSONException e) {
e.printStackTrace();
}
}

How do i parse large json files with json.simple?

I am new to JSON and I am learning using the json.simple library. I try to parse a large json file, but all i get is “OutOfMemoryError: GC overhead limit exceeded”. How can i parse large json files?
this is my code:
private static void fillPublications() throws FileNotFoundException, IOException, SQLException {
JSONParser parser = new JSONParser();
try {
String username = System.getProperty("user.name");
String filename = "Datenbank";
Object jsonData = parser.parse(new FileReader("C:\\Users\\" + username + "\\Desktop\\JSON\\" + filename + ".json"));
ArrayList<String[]> list = new ArrayList<String[]>();
JSONArray jsonArray = (JSONArray) jsonData;
Iterator iterator = jsonArray.iterator();
String name = "";
Integer count = 0;
while (iterator.hasNext()) {
String[] database = new String[11];
JSONObject obj = (JSONObject) iterator.next();
if(obj.containsKey("title")){
database[0] = (String) obj.get("title");
}
if(obj.containsKey("year")){
database[1] = obj.get("year").toString();
}
if(obj.containsKey("keywords")){
JSONArray keywords = (JSONArray) obj.get("keywords");
Iterator<String> i = keywords.iterator();
String key = "";
while (i.hasNext()) {
key = key + i.next() + "#";
}
if(key.length() > 0 && key.charAt(key.length()-1)=='#'){
key = key.substring(0, key.length()-1);
}
database[2] = key;
}
if(obj.containsKey("pages")){
database[3] = (String) obj.get("pages");
}
if(obj.containsKey("volume")){
database[4] = (String) obj.get("volume");
}
if(obj.containsKey("abstract")){
database[5] = (String) obj.get("abstract");
}
if(obj.containsKey("identifiers")){
JSONObject identifiers = (JSONObject) obj.get("identifiers");
database[6] = (String) identifiers.get("doi");
}
if(obj.containsKey("type")){
database[8] = (String) obj.get("type");
}
if(obj.containsKey("authors")){
JSONArray arr = (JSONArray) obj.get("authors");
Iterator i = arr.iterator();
while(i.hasNext()){
JSONObject authorObject = (JSONObject) i.next();
name = name + (String) authorObject.get("first_name") + " " + (String) authorObject.get("last_name") + "#";
}
if(name.length() > 0 && name.charAt(name.length()-1)=='#'){
name = name.substring(0, name.length()-1);
}
database[10] = name;
}
list.add(database);
}
System.out.println(Arrays.toString(list.get(0)));
}catch (Exception e) {
System.err.println(e);
}
}
and this is what i get:
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
at java.lang.StringBuffer.toString(StringBuffer.java:673)
at org.json.simple.parser.Yylex.yylex(Yylex.java:598)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:92)
at JSONExtraction.fillAuthors(JSONExtraction.java:39)
at JSONExtraction.main(JSONExtraction.java:23)
C:\Users\b\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

JsonArray to List in Java

I have a problem with parsing JsonArray response.
I take JsonObject from JsonArray, parse it and set in entity message and then that message add to ArrayList.
Problem is that in ArrayList that I want to return I always have only one message. This must be some fundamental error but I cant find it.
public ArrayList<Message> getSearchInfo(String response) {
ArrayList<Message> searchResult = new ArrayList<Message>();
int jsonMessageId = -1;
String jsonDate = "";
String jsonText = "";
String jsonAutor = "";
String jsonSource = "";
int jsonThemeID = -1;
int jsonSourceID = -1;
try {
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject oneObject = jArray.getJSONObject(i);
Message m = new Message();
// Pulling items from the array
jsonMessageId = oneObject.getInt("MessageId");
jsonDate = oneObject.getString("CreatedDate");
jsonText = oneObject.getString("TextMessage");
jsonAutor = oneObject.getString("Autor");
jsonSource = oneObject.getString("Source");
jsonThemeID = oneObject.getInt("ThemeId");
jsonSourceID = oneObject.getInt("SourceId");
m.setMessageId(jsonMessageId);
m.setMessageText(jsonText);
m.setDate(jsonDate);
m.setAutor(jsonAutor);
m.setSource(jsonSource);
m.setThemeId(jsonThemeID);
m.setSourceId(jsonSourceID);
searchResult.add(m);
} catch (JSONException e) {
Log.d("URL EXC", "Exception 2");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return searchResult;
}
p.s. I use web-api as service and via android I take resources from service.
Any idea where is my mistake here?
You redefine your list every time in the loop.
Change your code from
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
try {
searchResult = new ArrayList<Message>();
To
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
searchResult = new ArrayList<Message>();
for (int i = 0; i < jArray.length(); i++) {
try {

How do you parse JSON with a colon in the name? Android/Java

For example: { "primary:title":"Little Red Riding Hood"}
My Parser in Java (Android) is always getting stuck because of the colon between primary and title. I can parse anything else with ease, I just need help in this.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TextView txtViewParsedValue;
private JSONObject jsonObject;
private JSONArray jsonArray;
String [] titles, links, mediaDescriptions, mediaCredits, descriptions, dcCreators, pubDates, categories;
String [] permalinks, texts; // guid
String [] rels, hrefs;
String [] urls, media, heights, widths; // media:content
String strParsedValue = "";
private String strJSONValue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
strJSONValue = readRawTextFile(this, R.raw.jsonextract);
txtViewParsedValue = (TextView) findViewById(R.id.text_view_1);
try {
parseJSON();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parseJSON() throws JSONException
{
txtViewParsedValue.setText("Parse 1");
jsonObject = new JSONObject(strJSONValue);
jsonArray = jsonObject.getJSONArray("item");
titles = new String[jsonArray.length()];
links = new String[jsonArray.length()];
permalinks = new String[jsonArray.length()];
texts = new String[jsonArray.length()];
mediaDescriptions = new String[jsonArray.length()];
mediaCredits = new String[jsonArray.length()];
descriptions = new String[jsonArray.length()];
dcCreators = new String[jsonArray.length()];
pubDates = new String[jsonArray.length()];
categories = new String[jsonArray.length()];
txtViewParsedValue.setText("Parse 2");
for (int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
titles[i] = object.getString("title");
links[i] = object.getString("link");
JSONObject guidObj = object.getJSONObject("guid");
permalinks[i] = guidObj.getString("isPermaLink");
texts[i] = guidObj.getString("text");
//mediaDescriptions[i] = object.getString("media:description");
//mediaCredits[i] = object.getString("media:credit");
// *** THE PARSER FAILS IF THE COMMENTED LINES ARE IMPLEMENTED BECAUSE
// OF THE : IN BETWEEN THE NAMES ***
descriptions[i] = object.getString("description");
//dcCreators[i] = object.getString("dc:creator");
pubDates[i] = object.getString("pubDate");
categories[i] = object.getString("category");
}
for (int i=0; i<jsonArray.length(); i++)
{
strParsedValue += "\nTitle: " + titles[i];
strParsedValue += "\nLink: " + links[i];
strParsedValue += "\nPermalink: " + permalinks[i];
strParsedValue += "\nText: " + texts[i];
strParsedValue += "\nMedia Description: " + mediaDescriptions[i];
strParsedValue += "\nMedia Credit: " + mediaCredits[i];
strParsedValue += "\nDescription: " + descriptions[i];
strParsedValue += "\nDC Creator: " + dcCreators[i];
strParsedValue += "\nPublication Date: " + pubDates[i];
strParsedValue += "\nCategory: " + categories[i];
strParsedValue += "\n";
}
txtViewParsedValue.setText(strParsedValue);
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
//text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
For one, and to answer your question, there is no issue with JSONObject and the org.json.* classes parsing keys with colons in them if they're properly formed. The following unit test passed which means it was able to parse your example scenario:
public void testParsingKeysWithColons() throws JSONException {
String raw = "{ \"primary:title\":\"Little Red Riding Hood\"}";
JSONObject obj = new JSONObject(raw);
String primaryTitle = obj.getString("primary:title");
assertEquals("Little Red Riding Hood", primaryTitle);
}
Another suggestion is that using arrays of Strings for your data is clumsy and you'd be much better organized using a data structure to represent your objects. Instead of string arrays for titles, links, descriptions; use an object that has these properties and make a list of the objects. For example:
public class MyDataStructure {
public String title;
public String primaryTitle;
public String link;
public String mediaDescription;
public static class Keys {
public static String title = "title";
public static String primaryTitle = "primary:title";
public static String link = "link";
public static String mediaDescription = "media:description";
}
}
And then you can make a "translator" class that does all the parsing for you and returns a list of your object. This is much easier to work with and keep track of. You never have to think about data misaligning or having more or less data in one of your arrays than you expected. You also have a much easier time testing where the problem is if your input data is missing anything or any of your json is malformed.
public class MyDataStructureTranslator {
public static List<MyDataStructure> parseJson(String rawJsonData) throws JSONException {
List<MyDataStructure> list = new ArrayList<MyDataStructure>();
JSONObject obj = new JSONObject(rawJsonData);
JSONArray arr = obj.getJSONArray("item");
for(int i = 0; i < arr.length(); i++) {
JSONObject current = arr.getJSONObject(i);
MyDataStructure item = new MyDataStructure();
item.title = current.getString(MyDataStructure.Keys.title);
item.primaryTitle = current.getString(MyDataStructure.Keys.primaryTitle);
item.link = current.getString(MyDataStructure.Keys.link);
item.mediaDescription = current.getString(MyDataStructure.Keys.mediaDescription);
list.add(item);
}
return list;
}
}
Since Java identifiers cannot have colons, just specify a json property name that maps to the exact json name like:
#JsonProperty("primary:title")
public String primaryTitle;

Categories

Resources