Mined and Summarized Use Cases For API: net.sf.json-lib

  1. XML wrapper JSON format issue

    None .. details

    1. package com.discursive.answers
    2. import java.io.InputStream
    3. import net.sf.json.JSON
    4. import net.sf.json.xml.XMLSerializer
    5. import org.apache.commons.io.IOUtils
    6. public class ConvertXMLtoJSON {
    7. public static void main(String[] args) throws Exception {
    8. InputStream is = ConvertXMLtoJSON.class.getResourceAsStream("sample-xml.xml")
    9. String xml = IOUtils.toString(is)
    10. XMLSerializer xmlSerializer = new XMLSerializer()
    11. JSON json = xmlSerializer.read(xml)
    12. System.out.println(json.toString(2))
    13. }
    14. }

  2. XML wrapper JSON format issue

    None .. details

    1. package com.discursive.answers
    2. import java.io.InputStream
    3. import net.sf.json.JSON
    4. import net.sf.json.xml.XMLSerializer
    5. import org.apache.commons.io.IOUtils
    6. public class ConvertXMLtoJSON {
    7. public static void main(String[] args) throws Exception {
    8. InputStream is = ConvertXMLtoJSON.class.getResourceAsStream("sample-xml.xml")
    9. String xml = IOUtils.toString(is)
    10. XMLSerializer xmlSerializer = new XMLSerializer()
    11. JSON json = xmlSerializer.read(xml)
    12. System.out.println(json.toString(2))
    13. }
    14. }

    • See Also (3)
    1. WSO2 ESB Unable to convert complete JSON data to XML

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package a.b.wso2
      2. import java.io.IOException
      3. import java.io.OutputStream
      4. import java.io.UnsupportedEncodingException
      5. import java.net.URL
      6. import net.sf.json.JSON
      7. import net.sf.json.xml.XMLSerializer
      8. import org.apache.axiom.om.OMElement
      9. import org.apache.axiom.om.OMOutputFormat
      10. import org.apache.axiom.om.util.AXIOMUtil
      11. import org.apache.axis2.AxisFault
      12. import org.apache.axis2.Constants
      13. import org.apache.axis2.context.MessageContext
      14. import org.apache.axis2.transport.MessageFormatter
      15. import org.apache.log4j.BasicConfigurator
      16. import org.apache.log4j.Logger
      17. public class WsoXtoJ implements MessageFormatter { Logger logger = Logger.getLogger("a.b.wso2converter")
      18. private static int counter=0
      19. public String convert(String xData) { counter++
      20. if (logger.isDebugEnabled()) { logger.debug("\n]]]]] (A"+counter+") converting xml\n " + xData + "\n-----")
      21. } try { String tran = "__ns__"
      22. XMLSerializer serializer = new XMLSerializer()
      23. OMElement e = AXIOMUtil.stringToOM(xData)
      24. OMElement b = (OMElement) e.getChildrenWithLocalName("Body").next()
      25. b = (OMElement) b.getChildElements().next()
      26. String xfrag = b.toStringWithConsume()
      27. String str = ""
      28. JSON j = serializer.read(xfrag)
      29. str = j.toString()
      30. String nstr = str.replaceAll("\"([a-zA-Z0-9_]+)" + tran + "([a-zA-Z0-9]+)\"(\\s*)(:)", "\"$1:$2\"$3:")
      31. //", "\"$1:$2\"")
      32. if (logger.isDebugEnabled()) { logger.debug("\n----- (A"+counter+") to json\n" + nstr+"\n[[[[[")
      33. } return nstr
      34. } catch (Exception e) { throw new RuntimeException(e)
      35. } } @Override public String formatSOAPAction(MessageContext msgCtxt, OMOutputFormat format, String soapActionString) { return null
      36. } @Override public byte[] getBytes(MessageContext ctx, OMOutputFormat format) throws AxisFault { String env=""
      37. try { OMElement element = ctx.getEnvelope().getBody().getFirstElement()
      38. String payload = this.convert(element.toString())
      39. return payload.getBytes(format.getCharSetEncoding())
      40. } catch (UnsupportedEncodingException e) { logger.error("(A"+counter+") error converting xml to json "+ctx.getEnvelope().toString())
      41. throw AxisFault.makeFault(e)
      42. } } @Override public String getContentType(MessageContext msgCtxt, OMOutputFormat format, String soapActionString) { String contentType = (String) msgCtxt.getProperty(Constants.Configuration.CONTENT_TYPE)
      43. String encoding = format.getCharSetEncoding()
      44. if (contentType == null) { contentType = (String) msgCtxt.getProperty(Constants.Configuration.MESSAGE_TYPE)
      45. } if (encoding != null) { contentType += "
      46. charset=" + encoding
      47. } return contentType
      48. } @Override public URL getTargetAddress(MessageContext msgCtxt, OMOutputFormat format, URL targetURL) throws AxisFault { return targetURL
      49. } @Override public void writeTo(MessageContext msgCtxt, OMOutputFormat format, OutputStream out, boolean preserve) throws AxisFault { try { out.write(this.getBytes(msgCtxt, format))
      50. out.flush()
      51. } catch (IOException e) { throw AxisFault.makeFault(e)
      52. } }}

    2. WSO2 ESB Unable to convert complete JSON data to XML

      in this way we can smart proxy ie content route and mediate on transport and payload for ALL json based rest services through WSO2 with no issues This solves the problem I think camel does it this way by default). Here is the pom file and code place the jar into repository/components/lib you must update the messageformatter and messagebuilder mappings for content type application/json in axis2.xml . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package a.b.wso2
      2. import java.io.InputStream
      3. import net.sf.json.JSON
      4. import net.sf.json.JSONSerializer
      5. import net.sf.json.xml.XMLSerializer
      6. import org.apache.axiom.om.OMElement
      7. import org.apache.axiom.om.util.AXIOMUtil
      8. import org.apache.axis2.AxisFault
      9. import org.apache.axis2.builder.Builder
      10. import org.apache.axis2.context.MessageContext
      11. import org.apache.commons.io.IOUtils
      12. import org.apache.log4j.Logger
      13. public class WsoJtoX implements Builder {
      14. Logger logger = Logger.getLogger("a.b.wso2converter")
      15. @Override
      16. public OMElement processDocument(
      17. InputStream is, String contentType, MessageContext messageContext) throws AxisFault {
      18. String jsonData = ""
      19. try {
      20. jsonData = IOUtils.toString(is, "UTF-8")
      21. String output = process(jsonData)
      22. OMElement e = AXIOMUtil.stringToOM(output)
      23. return e
      24. } catch (Exception e) {
      25. logger.error("error converting json string " + jsonData, e)
      26. if (e instanceof AxisFault) {
      27. throw (AxisFault) e
      28. }
      29. throw new AxisFault("(B" + counter + ") error converting json to xml", e)
      30. }
      31. }
      32. static int counter = 0
      33. public String process(String jsonData) throws AxisFault {
      34. try {
      35. String tran = "__ns__"
      36. jsonData = jsonData.replace("\r", "").trim()
      37. //jsonData=jsonData.replace("\n", "")
      38. String decoded =
      39. (jsonData.replaceAll(
      40. "\"([a-zA-Z0-9_]*)\\:([a-zA-Z0-9]*)\"(\\s*)(:)", "\"$1" + tran + "$2\"$3:"))
      41. counter++
      42. if (logger.isDebugEnabled()) {
      43. logger.debug("\n>>>>> (B" + counter + ") converting json\n " + jsonData + "\n====")
      44. }
      45. XMLSerializer serializer = new XMLSerializer()
      46. JSON json = JSONSerializer.toJSON(decoded)
      47. String xml = serializer.write(json)
      48. //add in the soap stuff StringBuilder sb = new StringBuilder()
      49. sb.append(
      50. "<soap:Envelope xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\"> <soap:Body>")
      51. sb.append(xml.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", ""))
      52. sb.append("</soap:Body></soap:Envelope>")
      53. if (logger.isDebugEnabled()) {
      54. logger.debug("\n==== (B" + counter + ") to xml\n" + sb.toString() + "\n<<<<<")
      55. }
      56. return sb.toString()
      57. } catch (Exception e) {
      58. throw new AxisFault("(B" + counter + ") error transforming json to xml", e)
      59. }
      60. }
      61. }

    3. Parsing non-standard JSON

      You can use Json.Net to parse your input string. You can even make use of dynamic as below with the help of this-extension-class Tested with your string With pure Json.Net . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JObject jObj = (JObject)JsonConvert.DeserializeObject(json3)
      2. Console.WriteLine(jObj["names"]["en"])
      3. Console.WriteLine(jObj["status"])
      4. Console.WriteLine(jObj["start_time_xls"]["en"])
      5. Console.WriteLine(jObj["suspend_at"])

      Other Reactions
      1. @Stalker-Downvoter, Brave enough to explain your reason?

  3. how to retrieve JSON object from the JSON array

    You would essentially deserialize the json into its respective java objects and then use getters to retrieve the data you want. Below is the sample code for retrieving the ticketPrice from the given JSONObject Below are the imports for the above code source of JAR lib.sourceforge.net/ . .. details

    1. JSONObject objData = (JSONObject)JSONSerializer.toJSON(data)
    2. JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails")
    3. for(int nSize=0
    4. nSize < objTicketDetailsJsonArr.size()
    5. nSize++){ String ticketPrice = ""
    6. ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice")
    7. }

  4. Invalid json representation of date

    None .. details

    1. JsonConfig config = new JsonConfig()
    2. config.registerJsonValueProcessor( Class.forName("java.util.Date"), new NiceDateJsonBeanProcessor())
    3. final JSONObject jsonObjectForDate = JSONSerializer.toJSON(object, jsonConfig)

  5. Parse Json In Java How to read Inner Value

    I have only demonstrated how to get the ID but the same logic applies to the other values. . .. details

    1. JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString)
    2. JSONArray content = obj.getJSONObject("Demo").getJSONArray("CONTENT")
    3. java.util.Iterator<?> iterator = content.iterator()
    4. while (iterator.hasNext()) { JSONObject o = (JSONObject) iterator.next()
    5. System.out.println(o)
    6. System.out.println(o.get("ID"))
    7. // etc...}

    Positive Reactions
    1. thanks it working.

  6. Parse Json In Java How to read Inner Value

    Following is a sample code to reach the arrays inner objects specific to pattern you have provided. Note Above code is specifc to org.Json API. .. details

    1. String str = "{"+ "\"Demo\": {"+ "\"CONTENT\": ["+ " {"+ "\"ID\": \" 283 \","+ "\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+ "\"DURATION\": \"Full\""+ " },"+ "{"+ "\"ID\": \" 283 \","+ "\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+ "\"DURATION\": \"Full\""+ " }"+ "]"+ "}"+ "}"
    2. try { JSONObject jsr = new JSONObject(str)
    3. // JSON object with above data JSONObject demo = jsr.getJSONObject("Demo")
    4. // get Demo which is a JSON object inside jsr. JSONArray content = demo.getJSONArray("CONTENT")
    5. // get CONTENT which is Json array inside Demo for (int i = 0
    6. i < content.length()
    7. i++) { // iterate over array to get inner JSON objects and extract values inside JSONObject record = content.getJSONObject(i)
    8. // each item of Array is a JSON object String ID = record.getString("ID")
    9. String UID = record.getString("UID")
    10. String DURATION = record.getString("DURATION")
    11. }}catch (JSONException e) { e.printStackTrace()
    12. }

  7. How to Use JSON Accumulate Method With List?

    Maybe you can post the code of your JavaBean. You can use below code It will resolve your issue. .. details

    1. public String listToJsonString(List<StyleAttribute> attrs) { JSONObject jObject = new JSONObject()
    2. try { JSONArray jArray = new JSONArray()
    3. for (MyClass myObject: attrs) { JSONObject styleJSON = new JSONObject()
    4. styleJSON.put("name",myObject.getName())
    5. styleJSON.put("rollNumber", myObject.getRollNumber())
    6. jArray.add(styleJSON)
    7. } jObject.put("keyName", jArray)
    8. } catch (Exception jse) { } return jObject.toString()
    9. }

  8. I want to create a JSON document containing an Array of Addresses and Send with HTTP PUT

    It seems you want to create a JSON array of 5 different addresses.Here is code that creates the array and also sends it using put. See java HTTP-POST-using-JSON-in-Java Also you will have to download multiple libraries including . .. details

    1. import org.apache.http.HttpResponse
    2. import org.apache.http.client.HttpClient
    3. import org.apache.http.client.methods.HttpPut
    4. import org.apache.http.entity.StringEntity
    5. import org.apache.http.impl.client.DefaultHttpClient
    6. import net.sf.json.JSONArray
    7. import net.sf.json.JSONObject
    8. public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
    9. for (int i = 0
    10. i < 5
    11. i++) { JSONObject jsonAddressObj = new JSONObject()
    12. jsonAddressObj.put("address1", "a")
    13. jsonAddressObj.put("address2", "b")
    14. jsonAddressObj.put("city", "c")
    15. jsonAddressObj.put("state", "d")
    16. jsonAddressObj.put("postalCode", "e")
    17. jsonAddressArray.add(jsonAddressObj)
    18. } System.out.println(jsonAddressArray)
    19. HttpClient httpClient = new DefaultHttpClient()
    20. try { HttpPut request = new HttpPut("http://yourAddressHere")
    21. StringEntity params =new StringEntity(jsonAddressArray.toString())
    22. request.setEntity(params)
    23. HttpResponse response = httpClient.execute(request)
    24. System.out.println(response.toString())
    25. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
    26. }}

    Positive Reactions
    1. Thanks, and it's good your pointing that out.
    2. But +1 for everything else!.
    3. I just put the values to my jsonAddressObj.
    4. I do not want to send harcoded values to any of the fields.
    5. "address": { "address1": "9100 hopkins bulvard hopkins bulvard bulvard", "address2": "6700 hopkins bulvard hopkins bulvard bulvard", "city": "HOPKINS", "county": "Scott", "postalCode": "55379", "state": "VA" } How do I accomplish this using JSONArray and JSONObject?
    Other Reactions
    1. OK.
    2. I need to send the following as http request.
    3. Yeh, I got the feeling we're not using the same library.
    4. I did take out the for loop.
    5. That helped me.
    6. I want the address to be fetched from the EditText.
    7. That is the reason i used txtAddress1.getText().toString().
    8. And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
    9. Have you read anything about these technologies or checked the documentation?
    10. That did that work for me.
    11. Are you referring to a post or a put ?
    12. Is it just me or you're never adding anything to your jsonAddressArray ?
    13. Passed the jsonAddressObj to jsonObjSend.
    14. Http request is quite broad.
    15. I've uploaded the eclipse project to URL_https://dl.dropbox.com/u/6465647/InsertJsonExample.zip as I decided I'll make an online tutorial on my blog with this example.
    16. You should point that you have moved the JSONObject jsonAddressObj new JSONObject(); in the loop to create a new adress each time, because I don't think he will notice that.
    17. Here is what I want to do.
    18. it is a put method.
    19. Yeh your right...it's from the original code.

    • See Also (1)
    1. Create json object in servlet

      Your servlet returns only N number of JSON objects. But your giving that response to JSON array it may be the mistake try this code in your servlet . details

      Reactions - Positive 3, Negative 0, Others 0

      1. try{ Class.forName("com.mysql.jdbc.Driver").newInstance()
      2. Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/atmlivedetails","root","root")
      3. Statement st=con.createStatement()
      4. ResultSet rs=st.executeQuery("select atmbrno, atmbrname from location_stat where act_brname='"+br_id+"'")
      5. int i=0
      6. JSONArray jArray = new JSONArray()
      7. while(rs.next()){ String s = rs.getString("atmbrno")
      8. String t = rs.getString("atmbrname")
      9. JSONObject arrayObj = new JSONObject()
      10. arrayObj.put("atmbrno",s)
      11. arrayObj.put("atmbrname",t)
      12. jArray.add(i,arrayObj)
      13. i++
      14. } rs.close ()
      15. st.close ()
      16. out.print(jArray)
      17. }

      Positive Reactions
      1. Thanks @ColdHack I updated my answer.
      2. Wel done Bro...U r the best..it's working :D :D there is small thing wrong in ur code, jArray.put(i,arrayObj); and it should correct as jArray.add(i,arrayObj);Thanks again :D :D :D.
      3. ya i updated now thanks :).

  9. json object : Need to create a generic method to retrieve values

    Can we optimize it any further . . .. details

    1. package javaapplication1
    2. import java.util.StringTokenizer
    3. import net.sf.json.JSONException
    4. import net.sf.json.JSONObject
    5. public class Tokenization {
    6. public static void main(String args[]) {
    7. JSONObject parentData = new JSONObject()
    8. JSONObject childData = new JSONObject()
    9. parentData.put("command", "dance")
    10. parentData.put("uid", "123123123")
    11. childData.put("uid", "007")
    12. childData.put("username", "sup")
    13. childData.put("password", "bros")
    14. parentData.put("params", childData)
    15. System.out.println(parentData)
    16. String result = getValue(parentData, "params.uid")
    17. System.out.println("Result:" + result)
    18. }
    19. public static String getValue(JSONObject inputJson, String field) {
    20. String resultValue = null
    21. try {
    22. StringTokenizer stJson = new StringTokenizer(field, ".")
    23. int count = stJson.countTokens()
    24. JSONObject objecStore = new JSONObject()
    25. objecStore = inputJson
    26. while (stJson.hasMoreTokens()) {
    27. String st = stJson.nextToken()
    28. if (count > 1) {
    29. JSONObject objNode = objecStore.getJSONObject(st)
    30. count--
    31. objecStore = objNode
    32. } else {
    33. System.out.println(st)
    34. resultValue = objecStore.getString(st)
    35. }
    36. }
    37. } catch (JSONException e) {
    38. }
    39. return resultValue
    40. }
    41. }

  10. Retrieving all the keys in a nested json in java

    None .. details

    1. findKeys(JsonObject obj,List keys){List<String>keysFromObj=obj.keys()
    2. for(String key:keysFromObj){ if(obj.get(key).getClass()==JSONObject.class){ findKeys(obj.get(key),keys)
    3. }else{ keys.add(key)
    4. } }}

    • See Also (9)
    1. Retrieving all the keys in a nested json in java

      call the same function when your map.get(key).getClass()==JSONObject.Class. You can recursively traverse your JsonObject to get all keys.heres the pseudocode So suppose if your object is "a":1,"b":{"c":"hello","d":4.0}}the above function should give you "a","b","c","d" But if you want only "a","c","d" as your output,you can write . details

      Reactions - Positive 0, Negative 0, Others 0

      1. findKeys(JsonObject obj,List keys){List<String>keysFromObj=obj.keys()
      2. keys.addAll(keysFromObj)
      3. for(String key:keysFromObj){ if(obj.get(key).getClass()==JSONObject.class){ findKeys(obj.get(key),keys)
      4. } }}

    2. String to json conversion issue

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject()

    3. String to json conversion issue

      that is enough to do all the required things. Simple Example** First Prepare a String Now to parse the String Object U just have to pass the String to the constructor method That should do it and voila. details

      Reactions - Positive 3, Negative 6, Others 0

      1. JSONObject jObj = new JSONObject(jStr)

      Positive Reactions
      1. I just corrected it.
      2. I hope this helps.
      3. Thanks anyway for pointing that out.
      Negative Reactions
      1. Oh my bad!
      2. I just confused org.codehaus.jettison.json.JSONObject with net.sf.json.JSONObject .
      3. I'm realllly sorry!
      4. @David Grant is correct and I'm wrong.
      5. URL_http://json-lib.sourceforge.net/apidocs/jdk15/net/sf/json/JSONObject.html .
      6. Guys sorry for the wrong information.
      Other Reactions
      1. I take it back.
      2. -1: net.sf.json.JSONObject doesn't have a String constructor.

    4. String to json conversion issue

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jettison.json.JSONObject
      2. public static void run(JSONObject jsonObject) { System.out.println("in run-- "+jsonObject.getInt("person_id"))
      3. }public static void main(String[] args) throws Exception { System.out.println("here")
      4. String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}"
      5. JSONObject jsonObj = new JSONObject(json)
      6. run(jsonObj)
      7. }

    5. Create json object in servlet

      You need to add json-lib-2.4-jdk15.jar file to your project class-path and use following code to create JSON object. Console you will get output JSON data "key1":"value1","key2":"value2","key3":"value3" . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonData = new JSONObject()
      2. jsonData.put("key1", "value1")
      3. jsonData.put("key2", "value2")
      4. jsonData.put("key3", "value3")
      5. System.out.println("JSON data: "+jsonData.toString())

    6. Java OBJECT to JSONObject

      To add elements in this object we have used put method. Here is the full example code of FirstJSONJava.java is as follows To run this example you have to follow these few steps as follows Download JSON-lib jar and other supporting JarsAdd these jars to your classpathcreate and save FirstJSONJava.javaCompile it and execute Source Code . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import net.sf.json.JSONObject
      2. public class FirstJSONJava {
      3. public static void main(String args[]) {
      4. JSONObject object = new JSONObject()
      5. object.put("name", "Amit Kumar")
      6. object.put("Max.Marks", new Integer(100))
      7. object.put("Min.Marks", new Double(40))
      8. object.put("Scored", new Double(66.67))
      9. object.put("nickname", "Amit")
      10. System.out.println(object)
      11. }
      12. }

    7. Call Google Maps API in a loop to geocode dozens of addresses and get "java.lang.String cannot be cast to net.sf.json.JSONObject"

      . It looks like your error might be happening at this line Looking at your query method it also seems like you are swallowing the JSONException and returning an empty string which then cannot be cast to a JSONobject**. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject placemark = (JSONObject) query(json, "Placemark[0]")

    8. Convert json string to Java Map(JSONLib)

      So it is a map. . details

      Reactions - Positive 1, Negative 1, Others 0

      1. import java.util.Map
      2. import net.sf.json.JSONObject
      3. public class Foo {
      4. static String json = "{\"one\":\"won\",\"two\":2,\"three\":false}"
      5. public static void main(String[] args) {
      6. JSONObject jsonObject = JSONObject.fromObject(json)
      7. Map map = jsonObject
      8. System.out.println(map)
      9. }
      10. }

      Positive Reactions
      1. Wow, haven't noticed this:) Thanks!.
      Negative Reactions
      1. If there's any interest in further decoupling the resulting Map from JSON-lib, note that it's trivial to create a new Map from an existing Map's entries using a copy constructor, such as Map map new HashMap(jsonObject);.
      Other Reactions
      1. What if the JSON is nested?

    9. Parsing JSON in Spring MVC using Jackson JSON

      Your JSON has main-level Object with properties foo bar baz) and each property has different kind of value list string/boolean string/number). I'm using json lib from lib.sourceforge.net/ json-lib-2.1-jdk15.jar More samples here lib.sourceforge.net/usage.html . details

      Reactions - Positive 4, Negative 0, Others 0

      1. import net.sf.json.JSONObject
      2. ...public void send(){//put attributesMap m = New HashMap()
      3. m.put("send_to","my@admin.lan")
      4. m.put("email_subject","this is a test email")
      5. m.put("email_content","test email content")
      6. //generate JSON ObjectJSONObject json = JSONObject.fromObject(content)
      7. String message = json.toString()
      8. ...}public void receive(String jsonMessage){//parse attributesJSONObject json = JSONObject.fromObject(jsonMessage)
      9. String to = (String) json.get("send_to")
      10. String title = (String) json.get("email_subject")
      11. String content = (String) json.get("email_content")
      12. ...}

      Positive Reactions
      1. Sean, thanks anyway.
      2. Please: json-lib is very outdated.
      3. Jackson lib seems very cool.
      4. In my case, json-lib is enough.
      Other Reactions
      1. Use GSON or Jackson (which the OP explicitly mentioned).

  11. WSO2 ESB Unable to convert complete JSON data to XML

    None .. details

    1. package a.b.wso2
    2. import java.io.IOException
    3. import java.io.OutputStream
    4. import java.io.UnsupportedEncodingException
    5. import java.net.URL
    6. import net.sf.json.JSON
    7. import net.sf.json.xml.XMLSerializer
    8. import org.apache.axiom.om.OMElement
    9. import org.apache.axiom.om.OMOutputFormat
    10. import org.apache.axiom.om.util.AXIOMUtil
    11. import org.apache.axis2.AxisFault
    12. import org.apache.axis2.Constants
    13. import org.apache.axis2.context.MessageContext
    14. import org.apache.axis2.transport.MessageFormatter
    15. import org.apache.log4j.BasicConfigurator
    16. import org.apache.log4j.Logger
    17. public class WsoXtoJ implements MessageFormatter { Logger logger = Logger.getLogger("a.b.wso2converter")
    18. private static int counter=0
    19. public String convert(String xData) { counter++
    20. if (logger.isDebugEnabled()) { logger.debug("\n]]]]] (A"+counter+") converting xml\n " + xData + "\n-----")
    21. } try { String tran = "__ns__"
    22. XMLSerializer serializer = new XMLSerializer()
    23. OMElement e = AXIOMUtil.stringToOM(xData)
    24. OMElement b = (OMElement) e.getChildrenWithLocalName("Body").next()
    25. b = (OMElement) b.getChildElements().next()
    26. String xfrag = b.toStringWithConsume()
    27. String str = ""
    28. JSON j = serializer.read(xfrag)
    29. str = j.toString()
    30. String nstr = str.replaceAll("\"([a-zA-Z0-9_]+)" + tran + "([a-zA-Z0-9]+)\"(\\s*)(:)", "\"$1:$2\"$3:")
    31. //", "\"$1:$2\"")
    32. if (logger.isDebugEnabled()) { logger.debug("\n----- (A"+counter+") to json\n" + nstr+"\n[[[[[")
    33. } return nstr
    34. } catch (Exception e) { throw new RuntimeException(e)
    35. } } @Override public String formatSOAPAction(MessageContext msgCtxt, OMOutputFormat format, String soapActionString) { return null
    36. } @Override public byte[] getBytes(MessageContext ctx, OMOutputFormat format) throws AxisFault { String env=""
    37. try { OMElement element = ctx.getEnvelope().getBody().getFirstElement()
    38. String payload = this.convert(element.toString())
    39. return payload.getBytes(format.getCharSetEncoding())
    40. } catch (UnsupportedEncodingException e) { logger.error("(A"+counter+") error converting xml to json "+ctx.getEnvelope().toString())
    41. throw AxisFault.makeFault(e)
    42. } } @Override public String getContentType(MessageContext msgCtxt, OMOutputFormat format, String soapActionString) { String contentType = (String) msgCtxt.getProperty(Constants.Configuration.CONTENT_TYPE)
    43. String encoding = format.getCharSetEncoding()
    44. if (contentType == null) { contentType = (String) msgCtxt.getProperty(Constants.Configuration.MESSAGE_TYPE)
    45. } if (encoding != null) { contentType += "
    46. charset=" + encoding
    47. } return contentType
    48. } @Override public URL getTargetAddress(MessageContext msgCtxt, OMOutputFormat format, URL targetURL) throws AxisFault { return targetURL
    49. } @Override public void writeTo(MessageContext msgCtxt, OMOutputFormat format, OutputStream out, boolean preserve) throws AxisFault { try { out.write(this.getBytes(msgCtxt, format))
    50. out.flush()
    51. } catch (IOException e) { throw AxisFault.makeFault(e)
    52. } }}

  12. JSON/Java/Android: deserialisation from a String to a ArrayList&lt;Strings&gt;

    None .. details

    1. package test
    2. import java.util.ArrayList
    3. import net.sf.json.JSONObject
    4. public class Tst {public static void main(String[] args) { ArrayList<String> versuch=new ArrayList<String>()
    5. for(int i=1
    6. i<11
    7. i++){ String temp = "Time1234"+i+",MeanValue123"+i+"
    8. "
    9. System.out.println(temp)
    10. versuch.add(temp)
    11. } System.out.println(versuch)
    12. JSONObject jSONString = new JSONObject()
    13. for (String string:versuch) { //put each string in DBdata to a JSON-Object with key=time and value=value jSONString.put(string.substring(0, string.indexOf(",")), string.substring(string.indexOf(",")+1,string.indexOf("
    14. ")))
    15. } String output="data.ID=1234."+jSONString.toString()
    16. System.out.println(output)
    17. System.out.println(JSONDeconstruct(output))
    18. } public static ArrayList<String> JSONDeconstruct (String st) { ArrayList<String> out=new ArrayList<String>()
    19. int begpos=st.indexOf("{")
    20. int endpos=st.indexOf("}")
    21. int index=0
    22. String work=st.substring(begpos+1, endpos)
    23. String replaced=work.replace("\",\"", ",")
    24. work=replaced.replace("\":\"", ":")
    25. replaced=work.replace("\"","")+",definedend"
    26. System.out.println(replaced)
    27. while (!replaced.equals("definedend")) { out.add(replaced.substring(0,replaced.indexOf(":"))+","+replaced.substring(replaced.indexOf(":")+1, replaced.indexOf(","))+"
    28. ")
    29. String tempstring=replaced.substring(replaced.indexOf(",")+1)
    30. replaced=tempstring
    31. index++
    32. System.out.println("loop disassembly step"+index+" "+replaced)
    33. } return out
    34. }}

  13. Java json parsing exception

    None .. details

    1. $ java com.so.Q8187623Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactoryat net.sf.json.AbstractJSON.<clinit>(AbstractJSON.java:53)at net.sf.json.util.CycleDetectionStrategy.<clinit>(CycleDetectionStrategy.java:36)at net.sf.json.JsonConfig.<clinit>(JsonConfig.java:65)at net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:84)at com.so.Q8187623.main(Q8187623.java:15)Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactoryat java.net.URLClassLoader$1.run(URLClassLoader.java:202)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(URLClassLoader.java:190)at java.lang.ClassLoader.loadClass(ClassLoader.java:306)at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)at java.lang.ClassLoader.loadClass(ClassLoader.java:247)... 5 more

  14. Convert XML to JSON format

    None .. details

    1. package xml2json
    2. import java.util.ArrayList
    3. import java.util.List
    4. import net.sf.json.*
    5. import org.xml.sax.*
    6. import org.xml.sax.helpers.DefaultHandler
    7. public class SAXJsonParser extends DefaultHandler {
    8. static final String TEXTKEY = "_text"
    9. JSONObject result
    10. List<JSONObject> stack
    11. public SAXJsonParser() {}
    12. public JSONObject getJson() {
    13. return result
    14. }
    15. public String attributeName(String name) {
    16. return "@" + name
    17. }
    18. public void startDocument() throws SAXException {
    19. stack = new ArrayList<JSONObject>()
    20. stack.add(0, new JSONObject())
    21. }
    22. public void endDocument() throws SAXException {
    23. result = stack.remove(0)
    24. }
    25. public void startElement(String uri, String localName, String qName, Attributes attributes)
    26. throws SAXException {
    27. JSONObject work = new JSONObject()
    28. for (int ix = 0 ix < attributes.getLength() ix++)
    29. work.put(attributeName(attributes.getLocalName(ix)), attributes.getValue(ix))
    30. stack.add(0, work)
    31. }
    32. public void endElement(String uri, String localName, String qName) throws SAXException {
    33. JSONObject pop = stack.remove(0)
    34. // examine stack Object stashable = pop
    35. if (pop.containsKey(TEXTKEY)) {
    36. String value = pop.getString(TEXTKEY).trim()
    37. if (pop.keySet().size() == 1) stashable = value
    38. // single value else if (StringUtils.isBlank(value)) pop.remove(TEXTKEY)
    39. }
    40. JSONObject parent = stack.get(0)
    41. if (!parent.containsKey(
    42. localName)) { // add new object parent.put( localName, stashable )
    43. } else { // aggregate into arrays Object work = parent.get(localName)
    44. if (work instanceof JSONArray) {
    45. ((JSONArray) work).add(stashable)
    46. } else {
    47. parent.put(localName, new JSONArray())
    48. parent.getJSONArray(localName).add(work)
    49. parent.getJSONArray(localName).add(stashable)
    50. }
    51. }
    52. }
    53. public void characters(char ch[], int start, int length) throws SAXException {
    54. JSONObject work = stack.get(0)
    55. // aggregate characters String value = (work.containsKey(TEXTKEY) ? work.getString(TEXTKEY) : "" )
    56. work.put(TEXTKEY, value + new String(ch, start, length))
    57. }
    58. public void warning(SAXParseException e) throws SAXException {
    59. System.out.println("warning e=" + e.getMessage())
    60. }
    61. public void error(SAXParseException e) throws SAXException {
    62. System.err.println("error e=" + e.getMessage())
    63. }
    64. public void fatalError(SAXParseException e) throws SAXException {
    65. System.err.println("fatalError e=" + e.getMessage())
    66. throw e
    67. }
    68. }

  15. How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?

    It will help you with the Ajax call and the transformation back to Json from the string received in the http response. Ex your ajax call should be like that with JQuery and your servlet should look like that . .. details

    1. import java.io.*
    2. import javax.servlet.*
    3. import javax.servlet.http.*
    4. import net.sf.json.JSONArray
    5. public class JSONServlet extends HttpServlet {
    6. public void doGet(HttpServletRequest request, HttpServletResponse response)
    7. throws ServletException, IOException {
    8. JSONArray arrayObj = new JSONArray()
    9. arrayObj.add("D")
    10. arrayObj.add("A")
    11. arrayObj.add("L")
    12. arrayObj.add("D")
    13. arrayObj.add("A")
    14. arrayObj.add("TEST")
    15. PrintWriter out = response.getWriter()
    16. out.println(arrayObj)
    17. for (int i = 0 i < arrayObj.size() i++) {
    18. out.println(arrayObj.getString(i))
    19. }
    20. }
    21. }

    Negative Reactions
    1. that was a typing mistake, i've edited.secondly, i'm stuck on how to send that JSON array as response to the be received and read by the following AJAX line:document.getElementById("txtHint").innerHTML=xmlhttp.responseText;could you give a simple example to start with?
    Other Reactions
    1. see the edit in my response.

  16. How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?

    you basically use certain classes in java like the ones defined here convert the final output to a json string and then send it to javascript there you convert the json string back to json using eval or probably using a library called json2.js and you are all set here is code for the same for more . ok First This can't compile you have a duplicate variable array Second create a servlet/Struts Action/etc that will contains the code that will create your array. .. details

    1. ArrayList array=new ArrayList()
    2. array.add("D")
    3. array.add("A")
    4. array.add("L")
    5. JSONArray array = new JSONArray()

    Negative Reactions
    1. that was a typing mistake, i've edited.secondly, i'm stuck on how to send that JSON array as response to the be received and read by the following AJAX line:document.getElementById("txtHint").innerHTML=xmlhttp.responseText;could you give a simple example to start with?
    Other Reactions
    1. see the edit in my response.

  17. Json object from database in java

    If you have a Device objects json lib can serialize the object using methods as JSON. Saved as JsonEncode.java Compiled with Executed with Note classpath has DOS separator) Dependencies json-lib-2.4-jdk15.jar commons-lang-2.6.jar commons-logging-1.1.1.jar commons-collections-3.2.1.jar commons-beanutils-1.8.0.jar ezmorph-1.0.6.jar . .. details

    1. import java.util.*
    2. import net.sf.json.*
    3. public class JsonEncode {
    4. public static void main(String[] args) throws Exception {
    5. Device d1 = new Device("01", "CAM", "LivingRoom")
    6. Device d2 = new Device("15", "CAM", "Kitchen")
    7. List<Device> devices = new ArrayList<Device>(Arrays.asList(d1, d2))
    8. JSONArray serializedDevices = JSONArray.fromObject(devices)
    9. JSONObject jsonDevices = new JSONObject()
    10. jsonDevices.put("devices", serializedDevices)
    11. JSONObject json = new JSONObject()
    12. json.put("deviceList", jsonDevices)
    13. System.out.println(json)
    14. }
    15. public static class Device {
    16. Device(String id, String type, String name) {
    17. this.id = id
    18. this.type = type
    19. this.name = name
    20. }
    21. private String id
    22. public String getId() {
    23. return id
    24. }
    25. private String type
    26. public String getType() {
    27. return type
    28. }
    29. private String name
    30. public String getName() {
    31. return name
    32. }
    33. }
    34. }

  1. exception
      Chart will be rendered here
    1. XML wrapper JSON format issue

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.discursive.answers
      2. import java.io.InputStream
      3. import net.sf.json.JSON
      4. import net.sf.json.xml.XMLSerializer
      5. import org.apache.commons.io.IOUtils
      6. public class ConvertXMLtoJSON {
      7. public static void main(String[] args) throws Exception {
      8. InputStream is = ConvertXMLtoJSON.class.getResourceAsStream("sample-xml.xml")
      9. String xml = IOUtils.toString(is)
      10. XMLSerializer xmlSerializer = new XMLSerializer()
      11. JSON json = xmlSerializer.read(xml)
      12. System.out.println(json.toString(2))
      13. }
      14. }

    2. Json object from database in java

      If you have a Device objects json lib can serialize the object using methods as JSON. Saved as JsonEncode.java Compiled with Executed with Note classpath has DOS separator) Dependencies json-lib-2.4-jdk15.jar commons-lang-2.6.jar commons-logging-1.1.1.jar commons-collections-3.2.1.jar commons-beanutils-1.8.0.jar ezmorph-1.0.6.jar . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import net.sf.json.*
      3. public class JsonEncode {
      4. public static void main(String[] args) throws Exception {
      5. Device d1 = new Device("01", "CAM", "LivingRoom")
      6. Device d2 = new Device("15", "CAM", "Kitchen")
      7. List<Device> devices = new ArrayList<Device>(Arrays.asList(d1, d2))
      8. JSONArray serializedDevices = JSONArray.fromObject(devices)
      9. JSONObject jsonDevices = new JSONObject()
      10. jsonDevices.put("devices", serializedDevices)
      11. JSONObject json = new JSONObject()
      12. json.put("deviceList", jsonDevices)
      13. System.out.println(json)
      14. }
      15. public static class Device {
      16. Device(String id, String type, String name) {
      17. this.id = id
      18. this.type = type
      19. this.name = name
      20. }
      21. private String id
      22. public String getId() {
      23. return id
      24. }
      25. private String type
      26. public String getType() {
      27. return type
      28. }
      29. private String name
      30. public String getName() {
      31. return name
      32. }
      33. }
      34. }

    3. WSO2 ESB Unable to convert complete JSON data to XML

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package a.b.wso2
      2. import java.io.IOException
      3. import java.io.OutputStream
      4. import java.io.UnsupportedEncodingException
      5. import java.net.URL
      6. import net.sf.json.JSON
      7. import net.sf.json.xml.XMLSerializer
      8. import org.apache.axiom.om.OMElement
      9. import org.apache.axiom.om.OMOutputFormat
      10. import org.apache.axiom.om.util.AXIOMUtil
      11. import org.apache.axis2.AxisFault
      12. import org.apache.axis2.Constants
      13. import org.apache.axis2.context.MessageContext
      14. import org.apache.axis2.transport.MessageFormatter
      15. import org.apache.log4j.BasicConfigurator
      16. import org.apache.log4j.Logger
      17. public class WsoXtoJ implements MessageFormatter { Logger logger = Logger.getLogger("a.b.wso2converter")
      18. private static int counter=0
      19. public String convert(String xData) { counter++
      20. if (logger.isDebugEnabled()) { logger.debug("\n]]]]] (A"+counter+") converting xml\n " + xData + "\n-----")
      21. } try { String tran = "__ns__"
      22. XMLSerializer serializer = new XMLSerializer()
      23. OMElement e = AXIOMUtil.stringToOM(xData)
      24. OMElement b = (OMElement) e.getChildrenWithLocalName("Body").next()
      25. b = (OMElement) b.getChildElements().next()
      26. String xfrag = b.toStringWithConsume()
      27. String str = ""
      28. JSON j = serializer.read(xfrag)
      29. str = j.toString()
      30. String nstr = str.replaceAll("\"([a-zA-Z0-9_]+)" + tran + "([a-zA-Z0-9]+)\"(\\s*)(:)", "\"$1:$2\"$3:")
      31. //", "\"$1:$2\"")
      32. if (logger.isDebugEnabled()) { logger.debug("\n----- (A"+counter+") to json\n" + nstr+"\n[[[[[")
      33. } return nstr
      34. } catch (Exception e) { throw new RuntimeException(e)
      35. } } @Override public String formatSOAPAction(MessageContext msgCtxt, OMOutputFormat format, String soapActionString) { return null
      36. } @Override public byte[] getBytes(MessageContext ctx, OMOutputFormat format) throws AxisFault { String env=""
      37. try { OMElement element = ctx.getEnvelope().getBody().getFirstElement()
      38. String payload = this.convert(element.toString())
      39. return payload.getBytes(format.getCharSetEncoding())
      40. } catch (UnsupportedEncodingException e) { logger.error("(A"+counter+") error converting xml to json "+ctx.getEnvelope().toString())
      41. throw AxisFault.makeFault(e)
      42. } } @Override public String getContentType(MessageContext msgCtxt, OMOutputFormat format, String soapActionString) { String contentType = (String) msgCtxt.getProperty(Constants.Configuration.CONTENT_TYPE)
      43. String encoding = format.getCharSetEncoding()
      44. if (contentType == null) { contentType = (String) msgCtxt.getProperty(Constants.Configuration.MESSAGE_TYPE)
      45. } if (encoding != null) { contentType += "
      46. charset=" + encoding
      47. } return contentType
      48. } @Override public URL getTargetAddress(MessageContext msgCtxt, OMOutputFormat format, URL targetURL) throws AxisFault { return targetURL
      49. } @Override public void writeTo(MessageContext msgCtxt, OMOutputFormat format, OutputStream out, boolean preserve) throws AxisFault { try { out.write(this.getBytes(msgCtxt, format))
      50. out.flush()
      51. } catch (IOException e) { throw AxisFault.makeFault(e)
      52. } }}

    4. WSO2 ESB Unable to convert complete JSON data to XML

      in this way we can smart proxy ie content route and mediate on transport and payload for ALL json based rest services through WSO2 with no issues This solves the problem I think camel does it this way by default). Here is the pom file and code place the jar into repository/components/lib you must update the messageformatter and messagebuilder mappings for content type application/json in axis2.xml . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package a.b.wso2
      2. import java.io.InputStream
      3. import net.sf.json.JSON
      4. import net.sf.json.JSONSerializer
      5. import net.sf.json.xml.XMLSerializer
      6. import org.apache.axiom.om.OMElement
      7. import org.apache.axiom.om.util.AXIOMUtil
      8. import org.apache.axis2.AxisFault
      9. import org.apache.axis2.builder.Builder
      10. import org.apache.axis2.context.MessageContext
      11. import org.apache.commons.io.IOUtils
      12. import org.apache.log4j.Logger
      13. public class WsoJtoX implements Builder {
      14. Logger logger = Logger.getLogger("a.b.wso2converter")
      15. @Override
      16. public OMElement processDocument(
      17. InputStream is, String contentType, MessageContext messageContext) throws AxisFault {
      18. String jsonData = ""
      19. try {
      20. jsonData = IOUtils.toString(is, "UTF-8")
      21. String output = process(jsonData)
      22. OMElement e = AXIOMUtil.stringToOM(output)
      23. return e
      24. } catch (Exception e) {
      25. logger.error("error converting json string " + jsonData, e)
      26. if (e instanceof AxisFault) {
      27. throw (AxisFault) e
      28. }
      29. throw new AxisFault("(B" + counter + ") error converting json to xml", e)
      30. }
      31. }
      32. static int counter = 0
      33. public String process(String jsonData) throws AxisFault {
      34. try {
      35. String tran = "__ns__"
      36. jsonData = jsonData.replace("\r", "").trim()
      37. //jsonData=jsonData.replace("\n", "")
      38. String decoded =
      39. (jsonData.replaceAll(
      40. "\"([a-zA-Z0-9_]*)\\:([a-zA-Z0-9]*)\"(\\s*)(:)", "\"$1" + tran + "$2\"$3:"))
      41. counter++
      42. if (logger.isDebugEnabled()) {
      43. logger.debug("\n>>>>> (B" + counter + ") converting json\n " + jsonData + "\n====")
      44. }
      45. XMLSerializer serializer = new XMLSerializer()
      46. JSON json = JSONSerializer.toJSON(decoded)
      47. String xml = serializer.write(json)
      48. //add in the soap stuff StringBuilder sb = new StringBuilder()
      49. sb.append(
      50. "<soap:Envelope xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\"> <soap:Body>")
      51. sb.append(xml.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", ""))
      52. sb.append("</soap:Body></soap:Envelope>")
      53. if (logger.isDebugEnabled()) {
      54. logger.debug("\n==== (B" + counter + ") to xml\n" + sb.toString() + "\n<<<<<")
      55. }
      56. return sb.toString()
      57. } catch (Exception e) {
      58. throw new AxisFault("(B" + counter + ") error transforming json to xml", e)
      59. }
      60. }
      61. }

    5. String to json conversion issue

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jettison.json.JSONObject
      2. public static void run(JSONObject jsonObject) { System.out.println("in run-- "+jsonObject.getInt("person_id"))
      3. }public static void main(String[] args) throws Exception { System.out.println("here")
      4. String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}"
      5. JSONObject jsonObj = new JSONObject(json)
      6. run(jsonObj)
      7. }

    6. I want to create a JSON document containing an Array of Addresses and Send with HTTP PUT

      It seems you want to create a JSON array of 5 different addresses.Here is code that creates the array and also sends it using put. See java HTTP-POST-using-JSON-in-Java Also you will have to download multiple libraries including . details

      Reactions - Positive 5, Negative 0, Others 0

      1. import org.apache.http.HttpResponse
      2. import org.apache.http.client.HttpClient
      3. import org.apache.http.client.methods.HttpPut
      4. import org.apache.http.entity.StringEntity
      5. import org.apache.http.impl.client.DefaultHttpClient
      6. import net.sf.json.JSONArray
      7. import net.sf.json.JSONObject
      8. public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
      9. for (int i = 0
      10. i < 5
      11. i++) { JSONObject jsonAddressObj = new JSONObject()
      12. jsonAddressObj.put("address1", "a")
      13. jsonAddressObj.put("address2", "b")
      14. jsonAddressObj.put("city", "c")
      15. jsonAddressObj.put("state", "d")
      16. jsonAddressObj.put("postalCode", "e")
      17. jsonAddressArray.add(jsonAddressObj)
      18. } System.out.println(jsonAddressArray)
      19. HttpClient httpClient = new DefaultHttpClient()
      20. try { HttpPut request = new HttpPut("http://yourAddressHere")
      21. StringEntity params =new StringEntity(jsonAddressArray.toString())
      22. request.setEntity(params)
      23. HttpResponse response = httpClient.execute(request)
      24. System.out.println(response.toString())
      25. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
      26. }}

      Positive Reactions
      1. Thanks, and it's good your pointing that out.
      2. But +1 for everything else!.
      3. I just put the values to my jsonAddressObj.
      4. I do not want to send harcoded values to any of the fields.
      5. "address": { "address1": "9100 hopkins bulvard hopkins bulvard bulvard", "address2": "6700 hopkins bulvard hopkins bulvard bulvard", "city": "HOPKINS", "county": "Scott", "postalCode": "55379", "state": "VA" } How do I accomplish this using JSONArray and JSONObject?
      Other Reactions
      1. OK.
      2. I need to send the following as http request.
      3. Yeh, I got the feeling we're not using the same library.
      4. I did take out the for loop.
      5. That helped me.
      6. I want the address to be fetched from the EditText.
      7. That is the reason i used txtAddress1.getText().toString().
      8. And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
      9. Have you read anything about these technologies or checked the documentation?
      10. That did that work for me.
      11. Are you referring to a post or a put ?
      12. Is it just me or you're never adding anything to your jsonAddressArray ?
      13. Passed the jsonAddressObj to jsonObjSend.
      14. Http request is quite broad.
      15. I've uploaded the eclipse project to URL_https://dl.dropbox.com/u/6465647/InsertJsonExample.zip as I decided I'll make an online tutorial on my blog with this example.
      16. You should point that you have moved the JSONObject jsonAddressObj new JSONObject(); in the loop to create a new adress each time, because I don't think he will notice that.
      17. Here is what I want to do.
      18. it is a put method.
      19. Yeh your right...it's from the original code.

    7. How to Use JSON Accumulate Method With List?

      Maybe you can post the code of your JavaBean. You can use below code It will resolve your issue. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public String listToJsonString(List<StyleAttribute> attrs) { JSONObject jObject = new JSONObject()
      2. try { JSONArray jArray = new JSONArray()
      3. for (MyClass myObject: attrs) { JSONObject styleJSON = new JSONObject()
      4. styleJSON.put("name",myObject.getName())
      5. styleJSON.put("rollNumber", myObject.getRollNumber())
      6. jArray.add(styleJSON)
      7. } jObject.put("keyName", jArray)
      8. } catch (Exception jse) { } return jObject.toString()
      9. }

  2. jsonexception
      Chart will be rendered here
    1. Parse Json In Java How to read Inner Value

      Following is a sample code to reach the arrays inner objects specific to pattern you have provided. Note Above code is specifc to org.Json API. details

      Reactions - Positive 0, Negative 0, Others 0

      1. String str = "{"+ "\"Demo\": {"+ "\"CONTENT\": ["+ " {"+ "\"ID\": \" 283 \","+ "\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+ "\"DURATION\": \"Full\""+ " },"+ "{"+ "\"ID\": \" 283 \","+ "\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+ "\"DURATION\": \"Full\""+ " }"+ "]"+ "}"+ "}"
      2. try { JSONObject jsr = new JSONObject(str)
      3. // JSON object with above data JSONObject demo = jsr.getJSONObject("Demo")
      4. // get Demo which is a JSON object inside jsr. JSONArray content = demo.getJSONArray("CONTENT")
      5. // get CONTENT which is Json array inside Demo for (int i = 0
      6. i < content.length()
      7. i++) { // iterate over array to get inner JSON objects and extract values inside JSONObject record = content.getJSONObject(i)
      8. // each item of Array is a JSON object String ID = record.getString("ID")
      9. String UID = record.getString("UID")
      10. String DURATION = record.getString("DURATION")
      11. }}catch (JSONException e) { e.printStackTrace()
      12. }

    2. json object : Need to create a generic method to retrieve values

      Can we optimize it any further . . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package javaapplication1
      2. import java.util.StringTokenizer
      3. import net.sf.json.JSONException
      4. import net.sf.json.JSONObject
      5. public class Tokenization {
      6. public static void main(String args[]) {
      7. JSONObject parentData = new JSONObject()
      8. JSONObject childData = new JSONObject()
      9. parentData.put("command", "dance")
      10. parentData.put("uid", "123123123")
      11. childData.put("uid", "007")
      12. childData.put("username", "sup")
      13. childData.put("password", "bros")
      14. parentData.put("params", childData)
      15. System.out.println(parentData)
      16. String result = getValue(parentData, "params.uid")
      17. System.out.println("Result:" + result)
      18. }
      19. public static String getValue(JSONObject inputJson, String field) {
      20. String resultValue = null
      21. try {
      22. StringTokenizer stJson = new StringTokenizer(field, ".")
      23. int count = stJson.countTokens()
      24. JSONObject objecStore = new JSONObject()
      25. objecStore = inputJson
      26. while (stJson.hasMoreTokens()) {
      27. String st = stJson.nextToken()
      28. if (count > 1) {
      29. JSONObject objNode = objecStore.getJSONObject(st)
      30. count--
      31. objecStore = objNode
      32. } else {
      33. System.out.println(st)
      34. resultValue = objecStore.getString(st)
      35. }
      36. }
      37. } catch (JSONException e) {
      38. }
      39. return resultValue
      40. }
      41. }

    3. How to Use JSON Accumulate Method With List?

      Maybe you can post the code of your JavaBean. You can use below code It will resolve your issue. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public String listToJsonString(List<StyleAttribute> attrs) { JSONObject jObject = new JSONObject()
      2. try { JSONArray jArray = new JSONArray()
      3. for (MyClass myObject: attrs) { JSONObject styleJSON = new JSONObject()
      4. styleJSON.put("name",myObject.getName())
      5. styleJSON.put("rollNumber", myObject.getRollNumber())
      6. jArray.add(styleJSON)
      7. } jObject.put("keyName", jArray)
      8. } catch (Exception jse) { } return jObject.toString()
      9. }

  3. jsonarray
      Chart will be rendered here
    1. Parse Json In Java How to read Inner Value

      I have only demonstrated how to get the ID but the same logic applies to the other values. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString)
      2. JSONArray content = obj.getJSONObject("Demo").getJSONArray("CONTENT")
      3. java.util.Iterator<?> iterator = content.iterator()
      4. while (iterator.hasNext()) { JSONObject o = (JSONObject) iterator.next()
      5. System.out.println(o)
      6. System.out.println(o.get("ID"))
      7. // etc...}

      Positive Reactions
      1. thanks it working.

    2. Json object from database in java

      If you have a Device objects json lib can serialize the object using methods as JSON. Saved as JsonEncode.java Compiled with Executed with Note classpath has DOS separator) Dependencies json-lib-2.4-jdk15.jar commons-lang-2.6.jar commons-logging-1.1.1.jar commons-collections-3.2.1.jar commons-beanutils-1.8.0.jar ezmorph-1.0.6.jar . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import net.sf.json.*
      3. public class JsonEncode {
      4. public static void main(String[] args) throws Exception {
      5. Device d1 = new Device("01", "CAM", "LivingRoom")
      6. Device d2 = new Device("15", "CAM", "Kitchen")
      7. List<Device> devices = new ArrayList<Device>(Arrays.asList(d1, d2))
      8. JSONArray serializedDevices = JSONArray.fromObject(devices)
      9. JSONObject jsonDevices = new JSONObject()
      10. jsonDevices.put("devices", serializedDevices)
      11. JSONObject json = new JSONObject()
      12. json.put("deviceList", jsonDevices)
      13. System.out.println(json)
      14. }
      15. public static class Device {
      16. Device(String id, String type, String name) {
      17. this.id = id
      18. this.type = type
      19. this.name = name
      20. }
      21. private String id
      22. public String getId() {
      23. return id
      24. }
      25. private String type
      26. public String getType() {
      27. return type
      28. }
      29. private String name
      30. public String getName() {
      31. return name
      32. }
      33. }
      34. }

    3. I want to create a JSON document containing an Array of Addresses and Send with HTTP PUT

      It seems you want to create a JSON array of 5 different addresses.Here is code that creates the array and also sends it using put. See java HTTP-POST-using-JSON-in-Java Also you will have to download multiple libraries including . details

      Reactions - Positive 5, Negative 0, Others 0

      1. import org.apache.http.HttpResponse
      2. import org.apache.http.client.HttpClient
      3. import org.apache.http.client.methods.HttpPut
      4. import org.apache.http.entity.StringEntity
      5. import org.apache.http.impl.client.DefaultHttpClient
      6. import net.sf.json.JSONArray
      7. import net.sf.json.JSONObject
      8. public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
      9. for (int i = 0
      10. i < 5
      11. i++) { JSONObject jsonAddressObj = new JSONObject()
      12. jsonAddressObj.put("address1", "a")
      13. jsonAddressObj.put("address2", "b")
      14. jsonAddressObj.put("city", "c")
      15. jsonAddressObj.put("state", "d")
      16. jsonAddressObj.put("postalCode", "e")
      17. jsonAddressArray.add(jsonAddressObj)
      18. } System.out.println(jsonAddressArray)
      19. HttpClient httpClient = new DefaultHttpClient()
      20. try { HttpPut request = new HttpPut("http://yourAddressHere")
      21. StringEntity params =new StringEntity(jsonAddressArray.toString())
      22. request.setEntity(params)
      23. HttpResponse response = httpClient.execute(request)
      24. System.out.println(response.toString())
      25. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
      26. }}

      Positive Reactions
      1. Thanks, and it's good your pointing that out.
      2. But +1 for everything else!.
      3. I just put the values to my jsonAddressObj.
      4. I do not want to send harcoded values to any of the fields.
      5. "address": { "address1": "9100 hopkins bulvard hopkins bulvard bulvard", "address2": "6700 hopkins bulvard hopkins bulvard bulvard", "city": "HOPKINS", "county": "Scott", "postalCode": "55379", "state": "VA" } How do I accomplish this using JSONArray and JSONObject?
      Other Reactions
      1. OK.
      2. I need to send the following as http request.
      3. Yeh, I got the feeling we're not using the same library.
      4. I did take out the for loop.
      5. That helped me.
      6. I want the address to be fetched from the EditText.
      7. That is the reason i used txtAddress1.getText().toString().
      8. And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
      9. Have you read anything about these technologies or checked the documentation?
      10. That did that work for me.
      11. Are you referring to a post or a put ?
      12. Is it just me or you're never adding anything to your jsonAddressArray ?
      13. Passed the jsonAddressObj to jsonObjSend.
      14. Http request is quite broad.
      15. I've uploaded the eclipse project to URL_https://dl.dropbox.com/u/6465647/InsertJsonExample.zip as I decided I'll make an online tutorial on my blog with this example.
      16. You should point that you have moved the JSONObject jsonAddressObj new JSONObject(); in the loop to create a new adress each time, because I don't think he will notice that.
      17. Here is what I want to do.
      18. it is a put method.
      19. Yeh your right...it's from the original code.

    4. Create json object in servlet

      Your servlet returns only N number of JSON objects. But your giving that response to JSON array it may be the mistake try this code in your servlet . details

      Reactions - Positive 3, Negative 0, Others 0

      1. try{ Class.forName("com.mysql.jdbc.Driver").newInstance()
      2. Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/atmlivedetails","root","root")
      3. Statement st=con.createStatement()
      4. ResultSet rs=st.executeQuery("select atmbrno, atmbrname from location_stat where act_brname='"+br_id+"'")
      5. int i=0
      6. JSONArray jArray = new JSONArray()
      7. while(rs.next()){ String s = rs.getString("atmbrno")
      8. String t = rs.getString("atmbrname")
      9. JSONObject arrayObj = new JSONObject()
      10. arrayObj.put("atmbrno",s)
      11. arrayObj.put("atmbrname",t)
      12. jArray.add(i,arrayObj)
      13. i++
      14. } rs.close ()
      15. st.close ()
      16. out.print(jArray)
      17. }

      Positive Reactions
      1. Thanks @ColdHack I updated my answer.
      2. Wel done Bro...U r the best..it's working :D :D there is small thing wrong in ur code, jArray.put(i,arrayObj); and it should correct as jArray.add(i,arrayObj);Thanks again :D :D :D.
      3. ya i updated now thanks :).

    5. How to Use JSON Accumulate Method With List?

      Maybe you can post the code of your JavaBean. You can use below code It will resolve your issue. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public String listToJsonString(List<StyleAttribute> attrs) { JSONObject jObject = new JSONObject()
      2. try { JSONArray jArray = new JSONArray()
      3. for (MyClass myObject: attrs) { JSONObject styleJSON = new JSONObject()
      4. styleJSON.put("name",myObject.getName())
      5. styleJSON.put("rollNumber", myObject.getRollNumber())
      6. jArray.add(styleJSON)
      7. } jObject.put("keyName", jArray)
      8. } catch (Exception jse) { } return jObject.toString()
      9. }

    6. Convert XML to JSON format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package xml2json
      2. import java.util.ArrayList
      3. import java.util.List
      4. import net.sf.json.*
      5. import org.xml.sax.*
      6. import org.xml.sax.helpers.DefaultHandler
      7. public class SAXJsonParser extends DefaultHandler {
      8. static final String TEXTKEY = "_text"
      9. JSONObject result
      10. List<JSONObject> stack
      11. public SAXJsonParser() {}
      12. public JSONObject getJson() {
      13. return result
      14. }
      15. public String attributeName(String name) {
      16. return "@" + name
      17. }
      18. public void startDocument() throws SAXException {
      19. stack = new ArrayList<JSONObject>()
      20. stack.add(0, new JSONObject())
      21. }
      22. public void endDocument() throws SAXException {
      23. result = stack.remove(0)
      24. }
      25. public void startElement(String uri, String localName, String qName, Attributes attributes)
      26. throws SAXException {
      27. JSONObject work = new JSONObject()
      28. for (int ix = 0 ix < attributes.getLength() ix++)
      29. work.put(attributeName(attributes.getLocalName(ix)), attributes.getValue(ix))
      30. stack.add(0, work)
      31. }
      32. public void endElement(String uri, String localName, String qName) throws SAXException {
      33. JSONObject pop = stack.remove(0)
      34. // examine stack Object stashable = pop
      35. if (pop.containsKey(TEXTKEY)) {
      36. String value = pop.getString(TEXTKEY).trim()
      37. if (pop.keySet().size() == 1) stashable = value
      38. // single value else if (StringUtils.isBlank(value)) pop.remove(TEXTKEY)
      39. }
      40. JSONObject parent = stack.get(0)
      41. if (!parent.containsKey(
      42. localName)) { // add new object parent.put( localName, stashable )
      43. } else { // aggregate into arrays Object work = parent.get(localName)
      44. if (work instanceof JSONArray) {
      45. ((JSONArray) work).add(stashable)
      46. } else {
      47. parent.put(localName, new JSONArray())
      48. parent.getJSONArray(localName).add(work)
      49. parent.getJSONArray(localName).add(stashable)
      50. }
      51. }
      52. }
      53. public void characters(char ch[], int start, int length) throws SAXException {
      54. JSONObject work = stack.get(0)
      55. // aggregate characters String value = (work.containsKey(TEXTKEY) ? work.getString(TEXTKEY) : "" )
      56. work.put(TEXTKEY, value + new String(ch, start, length))
      57. }
      58. public void warning(SAXParseException e) throws SAXException {
      59. System.out.println("warning e=" + e.getMessage())
      60. }
      61. public void error(SAXParseException e) throws SAXException {
      62. System.err.println("error e=" + e.getMessage())
      63. }
      64. public void fatalError(SAXParseException e) throws SAXException {
      65. System.err.println("fatalError e=" + e.getMessage())
      66. throw e
      67. }
      68. }

    7. Parse Json In Java How to read Inner Value

      Following is a sample code to reach the arrays inner objects specific to pattern you have provided. Note Above code is specifc to org.Json API. details

      Reactions - Positive 0, Negative 0, Others 0

      1. String str = "{"+ "\"Demo\": {"+ "\"CONTENT\": ["+ " {"+ "\"ID\": \" 283 \","+ "\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+ "\"DURATION\": \"Full\""+ " },"+ "{"+ "\"ID\": \" 283 \","+ "\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+ "\"DURATION\": \"Full\""+ " }"+ "]"+ "}"+ "}"
      2. try { JSONObject jsr = new JSONObject(str)
      3. // JSON object with above data JSONObject demo = jsr.getJSONObject("Demo")
      4. // get Demo which is a JSON object inside jsr. JSONArray content = demo.getJSONArray("CONTENT")
      5. // get CONTENT which is Json array inside Demo for (int i = 0
      6. i < content.length()
      7. i++) { // iterate over array to get inner JSON objects and extract values inside JSONObject record = content.getJSONObject(i)
      8. // each item of Array is a JSON object String ID = record.getString("ID")
      9. String UID = record.getString("UID")
      10. String DURATION = record.getString("DURATION")
      11. }}catch (JSONException e) { e.printStackTrace()
      12. }

    8. How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?

      It will help you with the Ajax call and the transformation back to Json from the string received in the http response. Ex your ajax call should be like that with JQuery and your servlet should look like that . details

      Reactions - Positive 0, Negative 1, Others 0

      1. import java.io.*
      2. import javax.servlet.*
      3. import javax.servlet.http.*
      4. import net.sf.json.JSONArray
      5. public class JSONServlet extends HttpServlet {
      6. public void doGet(HttpServletRequest request, HttpServletResponse response)
      7. throws ServletException, IOException {
      8. JSONArray arrayObj = new JSONArray()
      9. arrayObj.add("D")
      10. arrayObj.add("A")
      11. arrayObj.add("L")
      12. arrayObj.add("D")
      13. arrayObj.add("A")
      14. arrayObj.add("TEST")
      15. PrintWriter out = response.getWriter()
      16. out.println(arrayObj)
      17. for (int i = 0 i < arrayObj.size() i++) {
      18. out.println(arrayObj.getString(i))
      19. }
      20. }
      21. }

      Negative Reactions
      1. that was a typing mistake, i've edited.secondly, i'm stuck on how to send that JSON array as response to the be received and read by the following AJAX line:document.getElementById("txtHint").innerHTML=xmlhttp.responseText;could you give a simple example to start with?
      Other Reactions
      1. see the edit in my response.

    9. how to retrieve JSON object from the JSON array

      You would essentially deserialize the json into its respective java objects and then use getters to retrieve the data you want. Below is the sample code for retrieving the ticketPrice from the given JSONObject Below are the imports for the above code source of JAR lib.sourceforge.net/ . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject objData = (JSONObject)JSONSerializer.toJSON(data)
      2. JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails")
      3. for(int nSize=0
      4. nSize < objTicketDetailsJsonArr.size()
      5. nSize++){ String ticketPrice = ""
      6. ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice")
      7. }

    10. How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?

      you basically use certain classes in java like the ones defined here convert the final output to a json string and then send it to javascript there you convert the json string back to json using eval or probably using a library called json2.js and you are all set here is code for the same for more . ok First This can't compile you have a duplicate variable array Second create a servlet/Struts Action/etc that will contains the code that will create your array. details

      Reactions - Positive 0, Negative 1, Others 0

      1. ArrayList array=new ArrayList()
      2. array.add("D")
      3. array.add("A")
      4. array.add("L")
      5. JSONArray array = new JSONArray()

      Negative Reactions
      1. that was a typing mistake, i've edited.secondly, i'm stuck on how to send that JSON array as response to the be received and read by the following AJAX line:document.getElementById("txtHint").innerHTML=xmlhttp.responseText;could you give a simple example to start with?
      Other Reactions
      1. see the edit in my response.

  4. jsonobject
      Chart will be rendered here
    1. Json object from database in java

      If you have a Device objects json lib can serialize the object using methods as JSON. Saved as JsonEncode.java Compiled with Executed with Note classpath has DOS separator) Dependencies json-lib-2.4-jdk15.jar commons-lang-2.6.jar commons-logging-1.1.1.jar commons-collections-3.2.1.jar commons-beanutils-1.8.0.jar ezmorph-1.0.6.jar . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import net.sf.json.*
      3. public class JsonEncode {
      4. public static void main(String[] args) throws Exception {
      5. Device d1 = new Device("01", "CAM", "LivingRoom")
      6. Device d2 = new Device("15", "CAM", "Kitchen")
      7. List<Device> devices = new ArrayList<Device>(Arrays.asList(d1, d2))
      8. JSONArray serializedDevices = JSONArray.fromObject(devices)
      9. JSONObject jsonDevices = new JSONObject()
      10. jsonDevices.put("devices", serializedDevices)
      11. JSONObject json = new JSONObject()
      12. json.put("deviceList", jsonDevices)
      13. System.out.println(json)
      14. }
      15. public static class Device {
      16. Device(String id, String type, String name) {
      17. this.id = id
      18. this.type = type
      19. this.name = name
      20. }
      21. private String id
      22. public String getId() {
      23. return id
      24. }
      25. private String type
      26. public String getType() {
      27. return type
      28. }
      29. private String name
      30. public String getName() {
      31. return name
      32. }
      33. }
      34. }

    2. String to json conversion issue

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject()

    3. String to json conversion issue

      that is enough to do all the required things. Simple Example** First Prepare a String Now to parse the String Object U just have to pass the String to the constructor method That should do it and voila. details

      Reactions - Positive 3, Negative 6, Others 0

      1. JSONObject jObj = new JSONObject(jStr)

      Positive Reactions
      1. I just corrected it.
      2. I hope this helps.
      3. Thanks anyway for pointing that out.
      Negative Reactions
      1. Oh my bad!
      2. I just confused org.codehaus.jettison.json.JSONObject with net.sf.json.JSONObject .
      3. I'm realllly sorry!
      4. @David Grant is correct and I'm wrong.
      5. URL_http://json-lib.sourceforge.net/apidocs/jdk15/net/sf/json/JSONObject.html .
      6. Guys sorry for the wrong information.
      Other Reactions
      1. I take it back.
      2. -1: net.sf.json.JSONObject doesn't have a String constructor.

    4. Java OBJECT to JSONObject

      To add elements in this object we have used put method. Here is the full example code of FirstJSONJava.java is as follows To run this example you have to follow these few steps as follows Download JSON-lib jar and other supporting JarsAdd these jars to your classpathcreate and save FirstJSONJava.javaCompile it and execute Source Code . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import net.sf.json.JSONObject
      2. public class FirstJSONJava {
      3. public static void main(String args[]) {
      4. JSONObject object = new JSONObject()
      5. object.put("name", "Amit Kumar")
      6. object.put("Max.Marks", new Integer(100))
      7. object.put("Min.Marks", new Double(40))
      8. object.put("Scored", new Double(66.67))
      9. object.put("nickname", "Amit")
      10. System.out.println(object)
      11. }
      12. }

    5. Invalid json representation of date

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonConfig config = new JsonConfig()
      2. config.registerJsonValueProcessor( Class.forName("java.util.Date"), new NiceDateJsonBeanProcessor())
      3. final JSONObject jsonObjectForDate = JSONSerializer.toJSON(object, jsonConfig)

    6. Call Google Maps API in a loop to geocode dozens of addresses and get "java.lang.String cannot be cast to net.sf.json.JSONObject"

      . It looks like your error might be happening at this line Looking at your query method it also seems like you are swallowing the JSONException and returning an empty string which then cannot be cast to a JSONobject**. details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject placemark = (JSONObject) query(json, "Placemark[0]")

    7. String to json conversion issue

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jettison.json.JSONObject
      2. public static void run(JSONObject jsonObject) { System.out.println("in run-- "+jsonObject.getInt("person_id"))
      3. }public static void main(String[] args) throws Exception { System.out.println("here")
      4. String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}"
      5. JSONObject jsonObj = new JSONObject(json)
      6. run(jsonObj)
      7. }

    8. Retrieving all the keys in a nested json in java

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. findKeys(JsonObject obj,List keys){List<String>keysFromObj=obj.keys()
      2. for(String key:keysFromObj){ if(obj.get(key).getClass()==JSONObject.class){ findKeys(obj.get(key),keys)
      3. }else{ keys.add(key)
      4. } }}

    9. Retrieving all the keys in a nested json in java

      call the same function when your map.get(key).getClass()==JSONObject.Class. You can recursively traverse your JsonObject to get all keys.heres the pseudocode So suppose if your object is "a":1,"b":{"c":"hello","d":4.0}}the above function should give you "a","b","c","d" But if you want only "a","c","d" as your output,you can write . details

      Reactions - Positive 0, Negative 0, Others 0

      1. findKeys(JsonObject obj,List keys){List<String>keysFromObj=obj.keys()
      2. keys.addAll(keysFromObj)
      3. for(String key:keysFromObj){ if(obj.get(key).getClass()==JSONObject.class){ findKeys(obj.get(key),keys)
      4. } }}

    10. I want to create a JSON document containing an Array of Addresses and Send with HTTP PUT

      It seems you want to create a JSON array of 5 different addresses.Here is code that creates the array and also sends it using put. See java HTTP-POST-using-JSON-in-Java Also you will have to download multiple libraries including . details

      Reactions - Positive 5, Negative 0, Others 0

      1. import org.apache.http.HttpResponse
      2. import org.apache.http.client.HttpClient
      3. import org.apache.http.client.methods.HttpPut
      4. import org.apache.http.entity.StringEntity
      5. import org.apache.http.impl.client.DefaultHttpClient
      6. import net.sf.json.JSONArray
      7. import net.sf.json.JSONObject
      8. public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
      9. for (int i = 0
      10. i < 5
      11. i++) { JSONObject jsonAddressObj = new JSONObject()
      12. jsonAddressObj.put("address1", "a")
      13. jsonAddressObj.put("address2", "b")
      14. jsonAddressObj.put("city", "c")
      15. jsonAddressObj.put("state", "d")
      16. jsonAddressObj.put("postalCode", "e")
      17. jsonAddressArray.add(jsonAddressObj)
      18. } System.out.println(jsonAddressArray)
      19. HttpClient httpClient = new DefaultHttpClient()
      20. try { HttpPut request = new HttpPut("http://yourAddressHere")
      21. StringEntity params =new StringEntity(jsonAddressArray.toString())
      22. request.setEntity(params)
      23. HttpResponse response = httpClient.execute(request)
      24. System.out.println(response.toString())
      25. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
      26. }}

      Positive Reactions
      1. Thanks, and it's good your pointing that out.
      2. But +1 for everything else!.
      3. I just put the values to my jsonAddressObj.
      4. I do not want to send harcoded values to any of the fields.
      5. "address": { "address1": "9100 hopkins bulvard hopkins bulvard bulvard", "address2": "6700 hopkins bulvard hopkins bulvard bulvard", "city": "HOPKINS", "county": "Scott", "postalCode": "55379", "state": "VA" } How do I accomplish this using JSONArray and JSONObject?
      Other Reactions
      1. OK.
      2. I need to send the following as http request.
      3. Yeh, I got the feeling we're not using the same library.
      4. I did take out the for loop.
      5. That helped me.
      6. I want the address to be fetched from the EditText.
      7. That is the reason i used txtAddress1.getText().toString().
      8. And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
      9. Have you read anything about these technologies or checked the documentation?
      10. That did that work for me.
      11. Are you referring to a post or a put ?
      12. Is it just me or you're never adding anything to your jsonAddressArray ?
      13. Passed the jsonAddressObj to jsonObjSend.
      14. Http request is quite broad.
      15. I've uploaded the eclipse project to URL_https://dl.dropbox.com/u/6465647/InsertJsonExample.zip as I decided I'll make an online tutorial on my blog with this example.
      16. You should point that you have moved the JSONObject jsonAddressObj new JSONObject(); in the loop to create a new adress each time, because I don't think he will notice that.
      17. Here is what I want to do.
      18. it is a put method.
      19. Yeh your right...it's from the original code.

    11. Create json object in servlet

      Your servlet returns only N number of JSON objects. But your giving that response to JSON array it may be the mistake try this code in your servlet . details

      Reactions - Positive 3, Negative 0, Others 0

      1. try{ Class.forName("com.mysql.jdbc.Driver").newInstance()
      2. Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/atmlivedetails","root","root")
      3. Statement st=con.createStatement()
      4. ResultSet rs=st.executeQuery("select atmbrno, atmbrname from location_stat where act_brname='"+br_id+"'")
      5. int i=0
      6. JSONArray jArray = new JSONArray()
      7. while(rs.next()){ String s = rs.getString("atmbrno")
      8. String t = rs.getString("atmbrname")
      9. JSONObject arrayObj = new JSONObject()
      10. arrayObj.put("atmbrno",s)
      11. arrayObj.put("atmbrname",t)
      12. jArray.add(i,arrayObj)
      13. i++
      14. } rs.close ()
      15. st.close ()
      16. out.print(jArray)
      17. }

      Positive Reactions
      1. Thanks @ColdHack I updated my answer.
      2. Wel done Bro...U r the best..it's working :D :D there is small thing wrong in ur code, jArray.put(i,arrayObj); and it should correct as jArray.add(i,arrayObj);Thanks again :D :D :D.
      3. ya i updated now thanks :).

    12. Create json object in servlet

      You need to add json-lib-2.4-jdk15.jar file to your project class-path and use following code to create JSON object. Console you will get output JSON data "key1":"value1","key2":"value2","key3":"value3" . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonData = new JSONObject()
      2. jsonData.put("key1", "value1")
      3. jsonData.put("key2", "value2")
      4. jsonData.put("key3", "value3")
      5. System.out.println("JSON data: "+jsonData.toString())

    13. Convert json string to Java Map(JSONLib)

      So it is a map. . details

      Reactions - Positive 1, Negative 1, Others 0

      1. import java.util.Map
      2. import net.sf.json.JSONObject
      3. public class Foo {
      4. static String json = "{\"one\":\"won\",\"two\":2,\"three\":false}"
      5. public static void main(String[] args) {
      6. JSONObject jsonObject = JSONObject.fromObject(json)
      7. Map map = jsonObject
      8. System.out.println(map)
      9. }
      10. }

      Positive Reactions
      1. Wow, haven't noticed this:) Thanks!.
      Negative Reactions
      1. If there's any interest in further decoupling the resulting Map from JSON-lib, note that it's trivial to create a new Map from an existing Map's entries using a copy constructor, such as Map map new HashMap(jsonObject);.
      Other Reactions
      1. What if the JSON is nested?

    14. JSON/Java/Android: deserialisation from a String to a ArrayList<Strings>

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package test
      2. import java.util.ArrayList
      3. import net.sf.json.JSONObject
      4. public class Tst {public static void main(String[] args) { ArrayList<String> versuch=new ArrayList<String>()
      5. for(int i=1
      6. i<11
      7. i++){ String temp = "Time1234"+i+",MeanValue123"+i+"
      8. "
      9. System.out.println(temp)
      10. versuch.add(temp)
      11. } System.out.println(versuch)
      12. JSONObject jSONString = new JSONObject()
      13. for (String string:versuch) { //put each string in DBdata to a JSON-Object with key=time and value=value jSONString.put(string.substring(0, string.indexOf(",")), string.substring(string.indexOf(",")+1,string.indexOf("
      14. ")))
      15. } String output="data.ID=1234."+jSONString.toString()
      16. System.out.println(output)
      17. System.out.println(JSONDeconstruct(output))
      18. } public static ArrayList<String> JSONDeconstruct (String st) { ArrayList<String> out=new ArrayList<String>()
      19. int begpos=st.indexOf("{")
      20. int endpos=st.indexOf("}")
      21. int index=0
      22. String work=st.substring(begpos+1, endpos)
      23. String replaced=work.replace("\",\"", ",")
      24. work=replaced.replace("\":\"", ":")
      25. replaced=work.replace("\"","")+",definedend"
      26. System.out.println(replaced)
      27. while (!replaced.equals("definedend")) { out.add(replaced.substring(0,replaced.indexOf(":"))+","+replaced.substring(replaced.indexOf(":")+1, replaced.indexOf(","))+"
      28. ")
      29. String tempstring=replaced.substring(replaced.indexOf(",")+1)
      30. replaced=tempstring
      31. index++
      32. System.out.println("loop disassembly step"+index+" "+replaced)
      33. } return out
      34. }}

    15. json object : Need to create a generic method to retrieve values

      Can we optimize it any further . . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package javaapplication1
      2. import java.util.StringTokenizer
      3. import net.sf.json.JSONException
      4. import net.sf.json.JSONObject
      5. public class Tokenization {
      6. public static void main(String args[]) {
      7. JSONObject parentData = new JSONObject()
      8. JSONObject childData = new JSONObject()
      9. parentData.put("command", "dance")
      10. parentData.put("uid", "123123123")
      11. childData.put("uid", "007")
      12. childData.put("username", "sup")
      13. childData.put("password", "bros")
      14. parentData.put("params", childData)
      15. System.out.println(parentData)
      16. String result = getValue(parentData, "params.uid")
      17. System.out.println("Result:" + result)
      18. }
      19. public static String getValue(JSONObject inputJson, String field) {
      20. String resultValue = null
      21. try {
      22. StringTokenizer stJson = new StringTokenizer(field, ".")
      23. int count = stJson.countTokens()
      24. JSONObject objecStore = new JSONObject()
      25. objecStore = inputJson
      26. while (stJson.hasMoreTokens()) {
      27. String st = stJson.nextToken()
      28. if (count > 1) {
      29. JSONObject objNode = objecStore.getJSONObject(st)
      30. count--
      31. objecStore = objNode
      32. } else {
      33. System.out.println(st)
      34. resultValue = objecStore.getString(st)
      35. }
      36. }
      37. } catch (JSONException e) {
      38. }
      39. return resultValue
      40. }
      41. }

    16. How to Use JSON Accumulate Method With List?

      Maybe you can post the code of your JavaBean. You can use below code It will resolve your issue. details

      Reactions - Positive 0, Negative 0, Others 0

      1. public String listToJsonString(List<StyleAttribute> attrs) { JSONObject jObject = new JSONObject()
      2. try { JSONArray jArray = new JSONArray()
      3. for (MyClass myObject: attrs) { JSONObject styleJSON = new JSONObject()
      4. styleJSON.put("name",myObject.getName())
      5. styleJSON.put("rollNumber", myObject.getRollNumber())
      6. jArray.add(styleJSON)
      7. } jObject.put("keyName", jArray)
      8. } catch (Exception jse) { } return jObject.toString()
      9. }

    17. Parsing JSON in Spring MVC using Jackson JSON

      Your JSON has main-level Object with properties foo bar baz) and each property has different kind of value list string/boolean string/number). I'm using json lib from lib.sourceforge.net/ json-lib-2.1-jdk15.jar More samples here lib.sourceforge.net/usage.html . details

      Reactions - Positive 4, Negative 0, Others 0

      1. import net.sf.json.JSONObject
      2. ...public void send(){//put attributesMap m = New HashMap()
      3. m.put("send_to","my@admin.lan")
      4. m.put("email_subject","this is a test email")
      5. m.put("email_content","test email content")
      6. //generate JSON ObjectJSONObject json = JSONObject.fromObject(content)
      7. String message = json.toString()
      8. ...}public void receive(String jsonMessage){//parse attributesJSONObject json = JSONObject.fromObject(jsonMessage)
      9. String to = (String) json.get("send_to")
      10. String title = (String) json.get("email_subject")
      11. String content = (String) json.get("email_content")
      12. ...}

      Positive Reactions
      1. Sean, thanks anyway.
      2. Please: json-lib is very outdated.
      3. Jackson lib seems very cool.
      4. In my case, json-lib is enough.
      Other Reactions
      1. Use GSON or Jackson (which the OP explicitly mentioned).

    18. Convert XML to JSON format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package xml2json
      2. import java.util.ArrayList
      3. import java.util.List
      4. import net.sf.json.*
      5. import org.xml.sax.*
      6. import org.xml.sax.helpers.DefaultHandler
      7. public class SAXJsonParser extends DefaultHandler {
      8. static final String TEXTKEY = "_text"
      9. JSONObject result
      10. List<JSONObject> stack
      11. public SAXJsonParser() {}
      12. public JSONObject getJson() {
      13. return result
      14. }
      15. public String attributeName(String name) {
      16. return "@" + name
      17. }
      18. public void startDocument() throws SAXException {
      19. stack = new ArrayList<JSONObject>()
      20. stack.add(0, new JSONObject())
      21. }
      22. public void endDocument() throws SAXException {
      23. result = stack.remove(0)
      24. }
      25. public void startElement(String uri, String localName, String qName, Attributes attributes)
      26. throws SAXException {
      27. JSONObject work = new JSONObject()
      28. for (int ix = 0 ix < attributes.getLength() ix++)
      29. work.put(attributeName(attributes.getLocalName(ix)), attributes.getValue(ix))
      30. stack.add(0, work)
      31. }
      32. public void endElement(String uri, String localName, String qName) throws SAXException {
      33. JSONObject pop = stack.remove(0)
      34. // examine stack Object stashable = pop
      35. if (pop.containsKey(TEXTKEY)) {
      36. String value = pop.getString(TEXTKEY).trim()
      37. if (pop.keySet().size() == 1) stashable = value
      38. // single value else if (StringUtils.isBlank(value)) pop.remove(TEXTKEY)
      39. }
      40. JSONObject parent = stack.get(0)
      41. if (!parent.containsKey(
      42. localName)) { // add new object parent.put( localName, stashable )
      43. } else { // aggregate into arrays Object work = parent.get(localName)
      44. if (work instanceof JSONArray) {
      45. ((JSONArray) work).add(stashable)
      46. } else {
      47. parent.put(localName, new JSONArray())
      48. parent.getJSONArray(localName).add(work)
      49. parent.getJSONArray(localName).add(stashable)
      50. }
      51. }
      52. }
      53. public void characters(char ch[], int start, int length) throws SAXException {
      54. JSONObject work = stack.get(0)
      55. // aggregate characters String value = (work.containsKey(TEXTKEY) ? work.getString(TEXTKEY) : "" )
      56. work.put(TEXTKEY, value + new String(ch, start, length))
      57. }
      58. public void warning(SAXParseException e) throws SAXException {
      59. System.out.println("warning e=" + e.getMessage())
      60. }
      61. public void error(SAXParseException e) throws SAXException {
      62. System.err.println("error e=" + e.getMessage())
      63. }
      64. public void fatalError(SAXParseException e) throws SAXException {
      65. System.err.println("fatalError e=" + e.getMessage())
      66. throw e
      67. }
      68. }

    19. how to retrieve JSON object from the JSON array

      You would essentially deserialize the json into its respective java objects and then use getters to retrieve the data you want. Below is the sample code for retrieving the ticketPrice from the given JSONObject Below are the imports for the above code source of JAR lib.sourceforge.net/ . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject objData = (JSONObject)JSONSerializer.toJSON(data)
      2. JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails")
      3. for(int nSize=0
      4. nSize < objTicketDetailsJsonArr.size()
      5. nSize++){ String ticketPrice = ""
      6. ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice")
      7. }

  5. arraylist
      Chart will be rendered here
    1. Json object from database in java

      If you have a Device objects json lib can serialize the object using methods as JSON. Saved as JsonEncode.java Compiled with Executed with Note classpath has DOS separator) Dependencies json-lib-2.4-jdk15.jar commons-lang-2.6.jar commons-logging-1.1.1.jar commons-collections-3.2.1.jar commons-beanutils-1.8.0.jar ezmorph-1.0.6.jar . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import net.sf.json.*
      3. public class JsonEncode {
      4. public static void main(String[] args) throws Exception {
      5. Device d1 = new Device("01", "CAM", "LivingRoom")
      6. Device d2 = new Device("15", "CAM", "Kitchen")
      7. List<Device> devices = new ArrayList<Device>(Arrays.asList(d1, d2))
      8. JSONArray serializedDevices = JSONArray.fromObject(devices)
      9. JSONObject jsonDevices = new JSONObject()
      10. jsonDevices.put("devices", serializedDevices)
      11. JSONObject json = new JSONObject()
      12. json.put("deviceList", jsonDevices)
      13. System.out.println(json)
      14. }
      15. public static class Device {
      16. Device(String id, String type, String name) {
      17. this.id = id
      18. this.type = type
      19. this.name = name
      20. }
      21. private String id
      22. public String getId() {
      23. return id
      24. }
      25. private String type
      26. public String getType() {
      27. return type
      28. }
      29. private String name
      30. public String getName() {
      31. return name
      32. }
      33. }
      34. }

    2. Convert XML to JSON format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package xml2json
      2. import java.util.ArrayList
      3. import java.util.List
      4. import net.sf.json.*
      5. import org.xml.sax.*
      6. import org.xml.sax.helpers.DefaultHandler
      7. public class SAXJsonParser extends DefaultHandler {
      8. static final String TEXTKEY = "_text"
      9. JSONObject result
      10. List<JSONObject> stack
      11. public SAXJsonParser() {}
      12. public JSONObject getJson() {
      13. return result
      14. }
      15. public String attributeName(String name) {
      16. return "@" + name
      17. }
      18. public void startDocument() throws SAXException {
      19. stack = new ArrayList<JSONObject>()
      20. stack.add(0, new JSONObject())
      21. }
      22. public void endDocument() throws SAXException {
      23. result = stack.remove(0)
      24. }
      25. public void startElement(String uri, String localName, String qName, Attributes attributes)
      26. throws SAXException {
      27. JSONObject work = new JSONObject()
      28. for (int ix = 0 ix < attributes.getLength() ix++)
      29. work.put(attributeName(attributes.getLocalName(ix)), attributes.getValue(ix))
      30. stack.add(0, work)
      31. }
      32. public void endElement(String uri, String localName, String qName) throws SAXException {
      33. JSONObject pop = stack.remove(0)
      34. // examine stack Object stashable = pop
      35. if (pop.containsKey(TEXTKEY)) {
      36. String value = pop.getString(TEXTKEY).trim()
      37. if (pop.keySet().size() == 1) stashable = value
      38. // single value else if (StringUtils.isBlank(value)) pop.remove(TEXTKEY)
      39. }
      40. JSONObject parent = stack.get(0)
      41. if (!parent.containsKey(
      42. localName)) { // add new object parent.put( localName, stashable )
      43. } else { // aggregate into arrays Object work = parent.get(localName)
      44. if (work instanceof JSONArray) {
      45. ((JSONArray) work).add(stashable)
      46. } else {
      47. parent.put(localName, new JSONArray())
      48. parent.getJSONArray(localName).add(work)
      49. parent.getJSONArray(localName).add(stashable)
      50. }
      51. }
      52. }
      53. public void characters(char ch[], int start, int length) throws SAXException {
      54. JSONObject work = stack.get(0)
      55. // aggregate characters String value = (work.containsKey(TEXTKEY) ? work.getString(TEXTKEY) : "" )
      56. work.put(TEXTKEY, value + new String(ch, start, length))
      57. }
      58. public void warning(SAXParseException e) throws SAXException {
      59. System.out.println("warning e=" + e.getMessage())
      60. }
      61. public void error(SAXParseException e) throws SAXException {
      62. System.err.println("error e=" + e.getMessage())
      63. }
      64. public void fatalError(SAXParseException e) throws SAXException {
      65. System.err.println("fatalError e=" + e.getMessage())
      66. throw e
      67. }
      68. }

    3. JSON/Java/Android: deserialisation from a String to a ArrayList<Strings>

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package test
      2. import java.util.ArrayList
      3. import net.sf.json.JSONObject
      4. public class Tst {public static void main(String[] args) { ArrayList<String> versuch=new ArrayList<String>()
      5. for(int i=1
      6. i<11
      7. i++){ String temp = "Time1234"+i+",MeanValue123"+i+"
      8. "
      9. System.out.println(temp)
      10. versuch.add(temp)
      11. } System.out.println(versuch)
      12. JSONObject jSONString = new JSONObject()
      13. for (String string:versuch) { //put each string in DBdata to a JSON-Object with key=time and value=value jSONString.put(string.substring(0, string.indexOf(",")), string.substring(string.indexOf(",")+1,string.indexOf("
      14. ")))
      15. } String output="data.ID=1234."+jSONString.toString()
      16. System.out.println(output)
      17. System.out.println(JSONDeconstruct(output))
      18. } public static ArrayList<String> JSONDeconstruct (String st) { ArrayList<String> out=new ArrayList<String>()
      19. int begpos=st.indexOf("{")
      20. int endpos=st.indexOf("}")
      21. int index=0
      22. String work=st.substring(begpos+1, endpos)
      23. String replaced=work.replace("\",\"", ",")
      24. work=replaced.replace("\":\"", ":")
      25. replaced=work.replace("\"","")+",definedend"
      26. System.out.println(replaced)
      27. while (!replaced.equals("definedend")) { out.add(replaced.substring(0,replaced.indexOf(":"))+","+replaced.substring(replaced.indexOf(":")+1, replaced.indexOf(","))+"
      28. ")
      29. String tempstring=replaced.substring(replaced.indexOf(",")+1)
      30. replaced=tempstring
      31. index++
      32. System.out.println("loop disassembly step"+index+" "+replaced)
      33. } return out
      34. }}

    4. How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?

      you basically use certain classes in java like the ones defined here convert the final output to a json string and then send it to javascript there you convert the json string back to json using eval or probably using a library called json2.js and you are all set here is code for the same for more . ok First This can't compile you have a duplicate variable array Second create a servlet/Struts Action/etc that will contains the code that will create your array. details

      Reactions - Positive 0, Negative 1, Others 0

      1. ArrayList array=new ArrayList()
      2. array.add("D")
      3. array.add("A")
      4. array.add("L")
      5. JSONArray array = new JSONArray()

      Negative Reactions
      1. that was a typing mistake, i've edited.secondly, i'm stuck on how to send that JSON array as response to the be received and read by the following AJAX line:document.getElementById("txtHint").innerHTML=xmlhttp.responseText;could you give a simple example to start with?
      Other Reactions
      1. see the edit in my response.

  6. system
      Chart will be rendered here
    1. Parse Json In Java How to read Inner Value

      I have only demonstrated how to get the ID but the same logic applies to the other values. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString)
      2. JSONArray content = obj.getJSONObject("Demo").getJSONArray("CONTENT")
      3. java.util.Iterator<?> iterator = content.iterator()
      4. while (iterator.hasNext()) { JSONObject o = (JSONObject) iterator.next()
      5. System.out.println(o)
      6. System.out.println(o.get("ID"))
      7. // etc...}

      Positive Reactions
      1. thanks it working.

    2. Java OBJECT to JSONObject

      To add elements in this object we have used put method. Here is the full example code of FirstJSONJava.java is as follows To run this example you have to follow these few steps as follows Download JSON-lib jar and other supporting JarsAdd these jars to your classpathcreate and save FirstJSONJava.javaCompile it and execute Source Code . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import net.sf.json.JSONObject
      2. public class FirstJSONJava {
      3. public static void main(String args[]) {
      4. JSONObject object = new JSONObject()
      5. object.put("name", "Amit Kumar")
      6. object.put("Max.Marks", new Integer(100))
      7. object.put("Min.Marks", new Double(40))
      8. object.put("Scored", new Double(66.67))
      9. object.put("nickname", "Amit")
      10. System.out.println(object)
      11. }
      12. }

    3. XML wrapper JSON format issue

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.discursive.answers
      2. import java.io.InputStream
      3. import net.sf.json.JSON
      4. import net.sf.json.xml.XMLSerializer
      5. import org.apache.commons.io.IOUtils
      6. public class ConvertXMLtoJSON {
      7. public static void main(String[] args) throws Exception {
      8. InputStream is = ConvertXMLtoJSON.class.getResourceAsStream("sample-xml.xml")
      9. String xml = IOUtils.toString(is)
      10. XMLSerializer xmlSerializer = new XMLSerializer()
      11. JSON json = xmlSerializer.read(xml)
      12. System.out.println(json.toString(2))
      13. }
      14. }

    4. Convert json string to Java Map(JSONLib)

      So it is a map. . details

      Reactions - Positive 1, Negative 1, Others 0

      1. import java.util.Map
      2. import net.sf.json.JSONObject
      3. public class Foo {
      4. static String json = "{\"one\":\"won\",\"two\":2,\"three\":false}"
      5. public static void main(String[] args) {
      6. JSONObject jsonObject = JSONObject.fromObject(json)
      7. Map map = jsonObject
      8. System.out.println(map)
      9. }
      10. }

      Positive Reactions
      1. Wow, haven't noticed this:) Thanks!.
      Negative Reactions
      1. If there's any interest in further decoupling the resulting Map from JSON-lib, note that it's trivial to create a new Map from an existing Map's entries using a copy constructor, such as Map map new HashMap(jsonObject);.
      Other Reactions
      1. What if the JSON is nested?

    5. Json object from database in java

      If you have a Device objects json lib can serialize the object using methods as JSON. Saved as JsonEncode.java Compiled with Executed with Note classpath has DOS separator) Dependencies json-lib-2.4-jdk15.jar commons-lang-2.6.jar commons-logging-1.1.1.jar commons-collections-3.2.1.jar commons-beanutils-1.8.0.jar ezmorph-1.0.6.jar . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import net.sf.json.*
      3. public class JsonEncode {
      4. public static void main(String[] args) throws Exception {
      5. Device d1 = new Device("01", "CAM", "LivingRoom")
      6. Device d2 = new Device("15", "CAM", "Kitchen")
      7. List<Device> devices = new ArrayList<Device>(Arrays.asList(d1, d2))
      8. JSONArray serializedDevices = JSONArray.fromObject(devices)
      9. JSONObject jsonDevices = new JSONObject()
      10. jsonDevices.put("devices", serializedDevices)
      11. JSONObject json = new JSONObject()
      12. json.put("deviceList", jsonDevices)
      13. System.out.println(json)
      14. }
      15. public static class Device {
      16. Device(String id, String type, String name) {
      17. this.id = id
      18. this.type = type
      19. this.name = name
      20. }
      21. private String id
      22. public String getId() {
      23. return id
      24. }
      25. private String type
      26. public String getType() {
      27. return type
      28. }
      29. private String name
      30. public String getName() {
      31. return name
      32. }
      33. }
      34. }

    6. String to json conversion issue

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. import org.codehaus.jettison.json.JSONObject
      2. public static void run(JSONObject jsonObject) { System.out.println("in run-- "+jsonObject.getInt("person_id"))
      3. }public static void main(String[] args) throws Exception { System.out.println("here")
      4. String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}"
      5. JSONObject jsonObj = new JSONObject(json)
      6. run(jsonObj)
      7. }

    7. I want to create a JSON document containing an Array of Addresses and Send with HTTP PUT

      It seems you want to create a JSON array of 5 different addresses.Here is code that creates the array and also sends it using put. See java HTTP-POST-using-JSON-in-Java Also you will have to download multiple libraries including . details

      Reactions - Positive 5, Negative 0, Others 0

      1. import org.apache.http.HttpResponse
      2. import org.apache.http.client.HttpClient
      3. import org.apache.http.client.methods.HttpPut
      4. import org.apache.http.entity.StringEntity
      5. import org.apache.http.impl.client.DefaultHttpClient
      6. import net.sf.json.JSONArray
      7. import net.sf.json.JSONObject
      8. public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
      9. for (int i = 0
      10. i < 5
      11. i++) { JSONObject jsonAddressObj = new JSONObject()
      12. jsonAddressObj.put("address1", "a")
      13. jsonAddressObj.put("address2", "b")
      14. jsonAddressObj.put("city", "c")
      15. jsonAddressObj.put("state", "d")
      16. jsonAddressObj.put("postalCode", "e")
      17. jsonAddressArray.add(jsonAddressObj)
      18. } System.out.println(jsonAddressArray)
      19. HttpClient httpClient = new DefaultHttpClient()
      20. try { HttpPut request = new HttpPut("http://yourAddressHere")
      21. StringEntity params =new StringEntity(jsonAddressArray.toString())
      22. request.setEntity(params)
      23. HttpResponse response = httpClient.execute(request)
      24. System.out.println(response.toString())
      25. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
      26. }}

      Positive Reactions
      1. Thanks, and it's good your pointing that out.
      2. But +1 for everything else!.
      3. I just put the values to my jsonAddressObj.
      4. I do not want to send harcoded values to any of the fields.
      5. "address": { "address1": "9100 hopkins bulvard hopkins bulvard bulvard", "address2": "6700 hopkins bulvard hopkins bulvard bulvard", "city": "HOPKINS", "county": "Scott", "postalCode": "55379", "state": "VA" } How do I accomplish this using JSONArray and JSONObject?
      Other Reactions
      1. OK.
      2. I need to send the following as http request.
      3. Yeh, I got the feeling we're not using the same library.
      4. I did take out the for loop.
      5. That helped me.
      6. I want the address to be fetched from the EditText.
      7. That is the reason i used txtAddress1.getText().toString().
      8. And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
      9. Have you read anything about these technologies or checked the documentation?
      10. That did that work for me.
      11. Are you referring to a post or a put ?
      12. Is it just me or you're never adding anything to your jsonAddressArray ?
      13. Passed the jsonAddressObj to jsonObjSend.
      14. Http request is quite broad.
      15. I've uploaded the eclipse project to URL_https://dl.dropbox.com/u/6465647/InsertJsonExample.zip as I decided I'll make an online tutorial on my blog with this example.
      16. You should point that you have moved the JSONObject jsonAddressObj new JSONObject(); in the loop to create a new adress each time, because I don't think he will notice that.
      17. Here is what I want to do.
      18. it is a put method.
      19. Yeh your right...it's from the original code.

    8. Create json object in servlet

      You need to add json-lib-2.4-jdk15.jar file to your project class-path and use following code to create JSON object. Console you will get output JSON data "key1":"value1","key2":"value2","key3":"value3" . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject jsonData = new JSONObject()
      2. jsonData.put("key1", "value1")
      3. jsonData.put("key2", "value2")
      4. jsonData.put("key3", "value3")
      5. System.out.println("JSON data: "+jsonData.toString())

    9. JSON/Java/Android: deserialisation from a String to a ArrayList<Strings>

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package test
      2. import java.util.ArrayList
      3. import net.sf.json.JSONObject
      4. public class Tst {public static void main(String[] args) { ArrayList<String> versuch=new ArrayList<String>()
      5. for(int i=1
      6. i<11
      7. i++){ String temp = "Time1234"+i+",MeanValue123"+i+"
      8. "
      9. System.out.println(temp)
      10. versuch.add(temp)
      11. } System.out.println(versuch)
      12. JSONObject jSONString = new JSONObject()
      13. for (String string:versuch) { //put each string in DBdata to a JSON-Object with key=time and value=value jSONString.put(string.substring(0, string.indexOf(",")), string.substring(string.indexOf(",")+1,string.indexOf("
      14. ")))
      15. } String output="data.ID=1234."+jSONString.toString()
      16. System.out.println(output)
      17. System.out.println(JSONDeconstruct(output))
      18. } public static ArrayList<String> JSONDeconstruct (String st) { ArrayList<String> out=new ArrayList<String>()
      19. int begpos=st.indexOf("{")
      20. int endpos=st.indexOf("}")
      21. int index=0
      22. String work=st.substring(begpos+1, endpos)
      23. String replaced=work.replace("\",\"", ",")
      24. work=replaced.replace("\":\"", ":")
      25. replaced=work.replace("\"","")+",definedend"
      26. System.out.println(replaced)
      27. while (!replaced.equals("definedend")) { out.add(replaced.substring(0,replaced.indexOf(":"))+","+replaced.substring(replaced.indexOf(":")+1, replaced.indexOf(","))+"
      28. ")
      29. String tempstring=replaced.substring(replaced.indexOf(",")+1)
      30. replaced=tempstring
      31. index++
      32. System.out.println("loop disassembly step"+index+" "+replaced)
      33. } return out
      34. }}

    10. json object : Need to create a generic method to retrieve values

      Can we optimize it any further . . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package javaapplication1
      2. import java.util.StringTokenizer
      3. import net.sf.json.JSONException
      4. import net.sf.json.JSONObject
      5. public class Tokenization {
      6. public static void main(String args[]) {
      7. JSONObject parentData = new JSONObject()
      8. JSONObject childData = new JSONObject()
      9. parentData.put("command", "dance")
      10. parentData.put("uid", "123123123")
      11. childData.put("uid", "007")
      12. childData.put("username", "sup")
      13. childData.put("password", "bros")
      14. parentData.put("params", childData)
      15. System.out.println(parentData)
      16. String result = getValue(parentData, "params.uid")
      17. System.out.println("Result:" + result)
      18. }
      19. public static String getValue(JSONObject inputJson, String field) {
      20. String resultValue = null
      21. try {
      22. StringTokenizer stJson = new StringTokenizer(field, ".")
      23. int count = stJson.countTokens()
      24. JSONObject objecStore = new JSONObject()
      25. objecStore = inputJson
      26. while (stJson.hasMoreTokens()) {
      27. String st = stJson.nextToken()
      28. if (count > 1) {
      29. JSONObject objNode = objecStore.getJSONObject(st)
      30. count--
      31. objecStore = objNode
      32. } else {
      33. System.out.println(st)
      34. resultValue = objecStore.getString(st)
      35. }
      36. }
      37. } catch (JSONException e) {
      38. }
      39. return resultValue
      40. }
      41. }

    11. Convert XML to JSON format

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package xml2json
      2. import java.util.ArrayList
      3. import java.util.List
      4. import net.sf.json.*
      5. import org.xml.sax.*
      6. import org.xml.sax.helpers.DefaultHandler
      7. public class SAXJsonParser extends DefaultHandler {
      8. static final String TEXTKEY = "_text"
      9. JSONObject result
      10. List<JSONObject> stack
      11. public SAXJsonParser() {}
      12. public JSONObject getJson() {
      13. return result
      14. }
      15. public String attributeName(String name) {
      16. return "@" + name
      17. }
      18. public void startDocument() throws SAXException {
      19. stack = new ArrayList<JSONObject>()
      20. stack.add(0, new JSONObject())
      21. }
      22. public void endDocument() throws SAXException {
      23. result = stack.remove(0)
      24. }
      25. public void startElement(String uri, String localName, String qName, Attributes attributes)
      26. throws SAXException {
      27. JSONObject work = new JSONObject()
      28. for (int ix = 0 ix < attributes.getLength() ix++)
      29. work.put(attributeName(attributes.getLocalName(ix)), attributes.getValue(ix))
      30. stack.add(0, work)
      31. }
      32. public void endElement(String uri, String localName, String qName) throws SAXException {
      33. JSONObject pop = stack.remove(0)
      34. // examine stack Object stashable = pop
      35. if (pop.containsKey(TEXTKEY)) {
      36. String value = pop.getString(TEXTKEY).trim()
      37. if (pop.keySet().size() == 1) stashable = value
      38. // single value else if (StringUtils.isBlank(value)) pop.remove(TEXTKEY)
      39. }
      40. JSONObject parent = stack.get(0)
      41. if (!parent.containsKey(
      42. localName)) { // add new object parent.put( localName, stashable )
      43. } else { // aggregate into arrays Object work = parent.get(localName)
      44. if (work instanceof JSONArray) {
      45. ((JSONArray) work).add(stashable)
      46. } else {
      47. parent.put(localName, new JSONArray())
      48. parent.getJSONArray(localName).add(work)
      49. parent.getJSONArray(localName).add(stashable)
      50. }
      51. }
      52. }
      53. public void characters(char ch[], int start, int length) throws SAXException {
      54. JSONObject work = stack.get(0)
      55. // aggregate characters String value = (work.containsKey(TEXTKEY) ? work.getString(TEXTKEY) : "" )
      56. work.put(TEXTKEY, value + new String(ch, start, length))
      57. }
      58. public void warning(SAXParseException e) throws SAXException {
      59. System.out.println("warning e=" + e.getMessage())
      60. }
      61. public void error(SAXParseException e) throws SAXException {
      62. System.err.println("error e=" + e.getMessage())
      63. }
      64. public void fatalError(SAXParseException e) throws SAXException {
      65. System.err.println("fatalError e=" + e.getMessage())
      66. throw e
      67. }
      68. }

  7. arrays
      Chart will be rendered here
    1. Json object from database in java

      If you have a Device objects json lib can serialize the object using methods as JSON. Saved as JsonEncode.java Compiled with Executed with Note classpath has DOS separator) Dependencies json-lib-2.4-jdk15.jar commons-lang-2.6.jar commons-logging-1.1.1.jar commons-collections-3.2.1.jar commons-beanutils-1.8.0.jar ezmorph-1.0.6.jar . details

      Reactions - Positive 0, Negative 0, Others 0

      1. import java.util.*
      2. import net.sf.json.*
      3. public class JsonEncode {
      4. public static void main(String[] args) throws Exception {
      5. Device d1 = new Device("01", "CAM", "LivingRoom")
      6. Device d2 = new Device("15", "CAM", "Kitchen")
      7. List<Device> devices = new ArrayList<Device>(Arrays.asList(d1, d2))
      8. JSONArray serializedDevices = JSONArray.fromObject(devices)
      9. JSONObject jsonDevices = new JSONObject()
      10. jsonDevices.put("devices", serializedDevices)
      11. JSONObject json = new JSONObject()
      12. json.put("deviceList", jsonDevices)
      13. System.out.println(json)
      14. }
      15. public static class Device {
      16. Device(String id, String type, String name) {
      17. this.id = id
      18. this.type = type
      19. this.name = name
      20. }
      21. private String id
      22. public String getId() {
      23. return id
      24. }
      25. private String type
      26. public String getType() {
      27. return type
      28. }
      29. private String name
      30. public String getName() {
      31. return name
      32. }
      33. }
      34. }

  8. writeline
      Chart will be rendered here
    1. Parsing non-standard JSON

      You can use Json.Net to parse your input string. You can even make use of dynamic as below with the help of this-extension-class Tested with your string With pure Json.Net . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JObject jObj = (JObject)JsonConvert.DeserializeObject(json3)
      2. Console.WriteLine(jObj["names"]["en"])
      3. Console.WriteLine(jObj["status"])
      4. Console.WriteLine(jObj["start_time_xls"]["en"])
      5. Console.WriteLine(jObj["suspend_at"])

      Other Reactions
      1. @Stalker-Downvoter, Brave enough to explain your reason?

  9. console
      Chart will be rendered here
    1. Parsing non-standard JSON

      You can use Json.Net to parse your input string. You can even make use of dynamic as below with the help of this-extension-class Tested with your string With pure Json.Net . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JObject jObj = (JObject)JsonConvert.DeserializeObject(json3)
      2. Console.WriteLine(jObj["names"]["en"])
      3. Console.WriteLine(jObj["status"])
      4. Console.WriteLine(jObj["start_time_xls"]["en"])
      5. Console.WriteLine(jObj["suspend_at"])

      Other Reactions
      1. @Stalker-Downvoter, Brave enough to explain your reason?

  10. xmlserializer
      Chart will be rendered here
    1. WSO2 ESB Unable to convert complete JSON data to XML

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package a.b.wso2
      2. import java.io.IOException
      3. import java.io.OutputStream
      4. import java.io.UnsupportedEncodingException
      5. import java.net.URL
      6. import net.sf.json.JSON
      7. import net.sf.json.xml.XMLSerializer
      8. import org.apache.axiom.om.OMElement
      9. import org.apache.axiom.om.OMOutputFormat
      10. import org.apache.axiom.om.util.AXIOMUtil
      11. import org.apache.axis2.AxisFault
      12. import org.apache.axis2.Constants
      13. import org.apache.axis2.context.MessageContext
      14. import org.apache.axis2.transport.MessageFormatter
      15. import org.apache.log4j.BasicConfigurator
      16. import org.apache.log4j.Logger
      17. public class WsoXtoJ implements MessageFormatter { Logger logger = Logger.getLogger("a.b.wso2converter")
      18. private static int counter=0
      19. public String convert(String xData) { counter++
      20. if (logger.isDebugEnabled()) { logger.debug("\n]]]]] (A"+counter+") converting xml\n " + xData + "\n-----")
      21. } try { String tran = "__ns__"
      22. XMLSerializer serializer = new XMLSerializer()
      23. OMElement e = AXIOMUtil.stringToOM(xData)
      24. OMElement b = (OMElement) e.getChildrenWithLocalName("Body").next()
      25. b = (OMElement) b.getChildElements().next()
      26. String xfrag = b.toStringWithConsume()
      27. String str = ""
      28. JSON j = serializer.read(xfrag)
      29. str = j.toString()
      30. String nstr = str.replaceAll("\"([a-zA-Z0-9_]+)" + tran + "([a-zA-Z0-9]+)\"(\\s*)(:)", "\"$1:$2\"$3:")
      31. //", "\"$1:$2\"")
      32. if (logger.isDebugEnabled()) { logger.debug("\n----- (A"+counter+") to json\n" + nstr+"\n[[[[[")
      33. } return nstr
      34. } catch (Exception e) { throw new RuntimeException(e)
      35. } } @Override public String formatSOAPAction(MessageContext msgCtxt, OMOutputFormat format, String soapActionString) { return null
      36. } @Override public byte[] getBytes(MessageContext ctx, OMOutputFormat format) throws AxisFault { String env=""
      37. try { OMElement element = ctx.getEnvelope().getBody().getFirstElement()
      38. String payload = this.convert(element.toString())
      39. return payload.getBytes(format.getCharSetEncoding())
      40. } catch (UnsupportedEncodingException e) { logger.error("(A"+counter+") error converting xml to json "+ctx.getEnvelope().toString())
      41. throw AxisFault.makeFault(e)
      42. } } @Override public String getContentType(MessageContext msgCtxt, OMOutputFormat format, String soapActionString) { String contentType = (String) msgCtxt.getProperty(Constants.Configuration.CONTENT_TYPE)
      43. String encoding = format.getCharSetEncoding()
      44. if (contentType == null) { contentType = (String) msgCtxt.getProperty(Constants.Configuration.MESSAGE_TYPE)
      45. } if (encoding != null) { contentType += "
      46. charset=" + encoding
      47. } return contentType
      48. } @Override public URL getTargetAddress(MessageContext msgCtxt, OMOutputFormat format, URL targetURL) throws AxisFault { return targetURL
      49. } @Override public void writeTo(MessageContext msgCtxt, OMOutputFormat format, OutputStream out, boolean preserve) throws AxisFault { try { out.write(this.getBytes(msgCtxt, format))
      50. out.flush()
      51. } catch (IOException e) { throw AxisFault.makeFault(e)
      52. } }}

    2. WSO2 ESB Unable to convert complete JSON data to XML

      in this way we can smart proxy ie content route and mediate on transport and payload for ALL json based rest services through WSO2 with no issues This solves the problem I think camel does it this way by default). Here is the pom file and code place the jar into repository/components/lib you must update the messageformatter and messagebuilder mappings for content type application/json in axis2.xml . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package a.b.wso2
      2. import java.io.InputStream
      3. import net.sf.json.JSON
      4. import net.sf.json.JSONSerializer
      5. import net.sf.json.xml.XMLSerializer
      6. import org.apache.axiom.om.OMElement
      7. import org.apache.axiom.om.util.AXIOMUtil
      8. import org.apache.axis2.AxisFault
      9. import org.apache.axis2.builder.Builder
      10. import org.apache.axis2.context.MessageContext
      11. import org.apache.commons.io.IOUtils
      12. import org.apache.log4j.Logger
      13. public class WsoJtoX implements Builder {
      14. Logger logger = Logger.getLogger("a.b.wso2converter")
      15. @Override
      16. public OMElement processDocument(
      17. InputStream is, String contentType, MessageContext messageContext) throws AxisFault {
      18. String jsonData = ""
      19. try {
      20. jsonData = IOUtils.toString(is, "UTF-8")
      21. String output = process(jsonData)
      22. OMElement e = AXIOMUtil.stringToOM(output)
      23. return e
      24. } catch (Exception e) {
      25. logger.error("error converting json string " + jsonData, e)
      26. if (e instanceof AxisFault) {
      27. throw (AxisFault) e
      28. }
      29. throw new AxisFault("(B" + counter + ") error converting json to xml", e)
      30. }
      31. }
      32. static int counter = 0
      33. public String process(String jsonData) throws AxisFault {
      34. try {
      35. String tran = "__ns__"
      36. jsonData = jsonData.replace("\r", "").trim()
      37. //jsonData=jsonData.replace("\n", "")
      38. String decoded =
      39. (jsonData.replaceAll(
      40. "\"([a-zA-Z0-9_]*)\\:([a-zA-Z0-9]*)\"(\\s*)(:)", "\"$1" + tran + "$2\"$3:"))
      41. counter++
      42. if (logger.isDebugEnabled()) {
      43. logger.debug("\n>>>>> (B" + counter + ") converting json\n " + jsonData + "\n====")
      44. }
      45. XMLSerializer serializer = new XMLSerializer()
      46. JSON json = JSONSerializer.toJSON(decoded)
      47. String xml = serializer.write(json)
      48. //add in the soap stuff StringBuilder sb = new StringBuilder()
      49. sb.append(
      50. "<soap:Envelope xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\"> <soap:Body>")
      51. sb.append(xml.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", ""))
      52. sb.append("</soap:Body></soap:Envelope>")
      53. if (logger.isDebugEnabled()) {
      54. logger.debug("\n==== (B" + counter + ") to xml\n" + sb.toString() + "\n<<<<<")
      55. }
      56. return sb.toString()
      57. } catch (Exception e) {
      58. throw new AxisFault("(B" + counter + ") error transforming json to xml", e)
      59. }
      60. }
      61. }

    3. XML wrapper JSON format issue

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. package com.discursive.answers
      2. import java.io.InputStream
      3. import net.sf.json.JSON
      4. import net.sf.json.xml.XMLSerializer
      5. import org.apache.commons.io.IOUtils
      6. public class ConvertXMLtoJSON {
      7. public static void main(String[] args) throws Exception {
      8. InputStream is = ConvertXMLtoJSON.class.getResourceAsStream("sample-xml.xml")
      9. String xml = IOUtils.toString(is)
      10. XMLSerializer xmlSerializer = new XMLSerializer()
      11. JSON json = xmlSerializer.read(xml)
      12. System.out.println(json.toString(2))
      13. }
      14. }

  11. jsonserializer
      Chart will be rendered here
    1. Parse Json In Java How to read Inner Value

      I have only demonstrated how to get the ID but the same logic applies to the other values. . details

      Reactions - Positive 1, Negative 0, Others 0

      1. JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString)
      2. JSONArray content = obj.getJSONObject("Demo").getJSONArray("CONTENT")
      3. java.util.Iterator<?> iterator = content.iterator()
      4. while (iterator.hasNext()) { JSONObject o = (JSONObject) iterator.next()
      5. System.out.println(o)
      6. System.out.println(o.get("ID"))
      7. // etc...}

      Positive Reactions
      1. thanks it working.

    2. Java json parsing exception

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. $ java com.so.Q8187623Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactoryat net.sf.json.AbstractJSON.<clinit>(AbstractJSON.java:53)at net.sf.json.util.CycleDetectionStrategy.<clinit>(CycleDetectionStrategy.java:36)at net.sf.json.JsonConfig.<clinit>(JsonConfig.java:65)at net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:84)at com.so.Q8187623.main(Q8187623.java:15)Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactoryat java.net.URLClassLoader$1.run(URLClassLoader.java:202)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(URLClassLoader.java:190)at java.lang.ClassLoader.loadClass(ClassLoader.java:306)at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)at java.lang.ClassLoader.loadClass(ClassLoader.java:247)... 5 more

    3. WSO2 ESB Unable to convert complete JSON data to XML

      in this way we can smart proxy ie content route and mediate on transport and payload for ALL json based rest services through WSO2 with no issues This solves the problem I think camel does it this way by default). Here is the pom file and code place the jar into repository/components/lib you must update the messageformatter and messagebuilder mappings for content type application/json in axis2.xml . details

      Reactions - Positive 0, Negative 0, Others 0

      1. package a.b.wso2
      2. import java.io.InputStream
      3. import net.sf.json.JSON
      4. import net.sf.json.JSONSerializer
      5. import net.sf.json.xml.XMLSerializer
      6. import org.apache.axiom.om.OMElement
      7. import org.apache.axiom.om.util.AXIOMUtil
      8. import org.apache.axis2.AxisFault
      9. import org.apache.axis2.builder.Builder
      10. import org.apache.axis2.context.MessageContext
      11. import org.apache.commons.io.IOUtils
      12. import org.apache.log4j.Logger
      13. public class WsoJtoX implements Builder {
      14. Logger logger = Logger.getLogger("a.b.wso2converter")
      15. @Override
      16. public OMElement processDocument(
      17. InputStream is, String contentType, MessageContext messageContext) throws AxisFault {
      18. String jsonData = ""
      19. try {
      20. jsonData = IOUtils.toString(is, "UTF-8")
      21. String output = process(jsonData)
      22. OMElement e = AXIOMUtil.stringToOM(output)
      23. return e
      24. } catch (Exception e) {
      25. logger.error("error converting json string " + jsonData, e)
      26. if (e instanceof AxisFault) {
      27. throw (AxisFault) e
      28. }
      29. throw new AxisFault("(B" + counter + ") error converting json to xml", e)
      30. }
      31. }
      32. static int counter = 0
      33. public String process(String jsonData) throws AxisFault {
      34. try {
      35. String tran = "__ns__"
      36. jsonData = jsonData.replace("\r", "").trim()
      37. //jsonData=jsonData.replace("\n", "")
      38. String decoded =
      39. (jsonData.replaceAll(
      40. "\"([a-zA-Z0-9_]*)\\:([a-zA-Z0-9]*)\"(\\s*)(:)", "\"$1" + tran + "$2\"$3:"))
      41. counter++
      42. if (logger.isDebugEnabled()) {
      43. logger.debug("\n>>>>> (B" + counter + ") converting json\n " + jsonData + "\n====")
      44. }
      45. XMLSerializer serializer = new XMLSerializer()
      46. JSON json = JSONSerializer.toJSON(decoded)
      47. String xml = serializer.write(json)
      48. //add in the soap stuff StringBuilder sb = new StringBuilder()
      49. sb.append(
      50. "<soap:Envelope xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\"> <soap:Body>")
      51. sb.append(xml.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", ""))
      52. sb.append("</soap:Body></soap:Envelope>")
      53. if (logger.isDebugEnabled()) {
      54. logger.debug("\n==== (B" + counter + ") to xml\n" + sb.toString() + "\n<<<<<")
      55. }
      56. return sb.toString()
      57. } catch (Exception e) {
      58. throw new AxisFault("(B" + counter + ") error transforming json to xml", e)
      59. }
      60. }
      61. }

    4. how to retrieve JSON object from the JSON array

      You would essentially deserialize the json into its respective java objects and then use getters to retrieve the data you want. Below is the sample code for retrieving the ticketPrice from the given JSONObject Below are the imports for the above code source of JAR lib.sourceforge.net/ . details

      Reactions - Positive 0, Negative 0, Others 0

      1. JSONObject objData = (JSONObject)JSONSerializer.toJSON(data)
      2. JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails")
      3. for(int nSize=0
      4. nSize < objTicketDetailsJsonArr.size()
      5. nSize++){ String ticketPrice = ""
      6. ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice")
      7. }

    5. Invalid json representation of date

      None details

      Reactions - Positive 0, Negative 0, Others 0

      1. JsonConfig config = new JsonConfig()
      2. config.registerJsonValueProcessor( Class.forName("java.util.Date"), new NiceDateJsonBeanProcessor())
      3. final JSONObject jsonObjectForDate = JSONSerializer.toJSON(object, jsonConfig)

All usage scenarios for API net.sf.json-lib
  • XML wrapper JSON format issue

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. package com.discursive.answers
    2. import java.io.InputStream
    3. import net.sf.json.JSON
    4. import net.sf.json.xml.XMLSerializer
    5. import org.apache.commons.io.IOUtils
    6. public class ConvertXMLtoJSON {
    7. public static void main(String[] args) throws Exception {
    8. InputStream is = ConvertXMLtoJSON.class.getResourceAsStream("sample-xml.xml")
    9. String xml = IOUtils.toString(is)
    10. XMLSerializer xmlSerializer = new XMLSerializer()
    11. JSON json = xmlSerializer.read(xml)
    12. System.out.println(json.toString(2))
    13. }
    14. }

  • how to retrieve JSON object from the JSON array

    You would essentially deserialize the json into its respective java objects and then use getters to retrieve the data you want. Below is the sample code for retrieving the ticketPrice from the given JSONObject Below are the imports for the above code source of JAR lib.sourceforge.net/ . details

    Reactions - Positive 0, Negative 0, Others 0

    1. JSONObject objData = (JSONObject)JSONSerializer.toJSON(data)
    2. JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails")
    3. for(int nSize=0
    4. nSize < objTicketDetailsJsonArr.size()
    5. nSize++){ String ticketPrice = ""
    6. ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice")
    7. }

  • Invalid json representation of date

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. JsonConfig config = new JsonConfig()
    2. config.registerJsonValueProcessor( Class.forName("java.util.Date"), new NiceDateJsonBeanProcessor())
    3. final JSONObject jsonObjectForDate = JSONSerializer.toJSON(object, jsonConfig)

  • Parse Json In Java How to read Inner Value

    I have only demonstrated how to get the ID but the same logic applies to the other values. . details

    Reactions - Positive 1, Negative 0, Others 0

    1. JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString)
    2. JSONArray content = obj.getJSONObject("Demo").getJSONArray("CONTENT")
    3. java.util.Iterator<?> iterator = content.iterator()
    4. while (iterator.hasNext()) { JSONObject o = (JSONObject) iterator.next()
    5. System.out.println(o)
    6. System.out.println(o.get("ID"))
    7. // etc...}

    Positive Reactions
    1. thanks it working.

  • Parse Json In Java How to read Inner Value

    Following is a sample code to reach the arrays inner objects specific to pattern you have provided. Note Above code is specifc to org.Json API. details

    Reactions - Positive 0, Negative 0, Others 0

    1. String str = "{"+ "\"Demo\": {"+ "\"CONTENT\": ["+ " {"+ "\"ID\": \" 283 \","+ "\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+ "\"DURATION\": \"Full\""+ " },"+ "{"+ "\"ID\": \" 283 \","+ "\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+ "\"DURATION\": \"Full\""+ " }"+ "]"+ "}"+ "}"
    2. try { JSONObject jsr = new JSONObject(str)
    3. // JSON object with above data JSONObject demo = jsr.getJSONObject("Demo")
    4. // get Demo which is a JSON object inside jsr. JSONArray content = demo.getJSONArray("CONTENT")
    5. // get CONTENT which is Json array inside Demo for (int i = 0
    6. i < content.length()
    7. i++) { // iterate over array to get inner JSON objects and extract values inside JSONObject record = content.getJSONObject(i)
    8. // each item of Array is a JSON object String ID = record.getString("ID")
    9. String UID = record.getString("UID")
    10. String DURATION = record.getString("DURATION")
    11. }}catch (JSONException e) { e.printStackTrace()
    12. }

  • How to Use JSON Accumulate Method With List?

    Maybe you can post the code of your JavaBean. You can use below code It will resolve your issue. details

    Reactions - Positive 0, Negative 0, Others 0

    1. public String listToJsonString(List<StyleAttribute> attrs) { JSONObject jObject = new JSONObject()
    2. try { JSONArray jArray = new JSONArray()
    3. for (MyClass myObject: attrs) { JSONObject styleJSON = new JSONObject()
    4. styleJSON.put("name",myObject.getName())
    5. styleJSON.put("rollNumber", myObject.getRollNumber())
    6. jArray.add(styleJSON)
    7. } jObject.put("keyName", jArray)
    8. } catch (Exception jse) { } return jObject.toString()
    9. }

  • I want to create a JSON document containing an Array of Addresses and Send with HTTP PUT

    It seems you want to create a JSON array of 5 different addresses.Here is code that creates the array and also sends it using put. See java HTTP-POST-using-JSON-in-Java Also you will have to download multiple libraries including . details

    Reactions - Positive 5, Negative 0, Others 0

    1. import org.apache.http.HttpResponse
    2. import org.apache.http.client.HttpClient
    3. import org.apache.http.client.methods.HttpPut
    4. import org.apache.http.entity.StringEntity
    5. import org.apache.http.impl.client.DefaultHttpClient
    6. import net.sf.json.JSONArray
    7. import net.sf.json.JSONObject
    8. public class JSONTest {public static void main(String args[]) { JSONArray jsonAddressArray = new JSONArray()
    9. for (int i = 0
    10. i < 5
    11. i++) { JSONObject jsonAddressObj = new JSONObject()
    12. jsonAddressObj.put("address1", "a")
    13. jsonAddressObj.put("address2", "b")
    14. jsonAddressObj.put("city", "c")
    15. jsonAddressObj.put("state", "d")
    16. jsonAddressObj.put("postalCode", "e")
    17. jsonAddressArray.add(jsonAddressObj)
    18. } System.out.println(jsonAddressArray)
    19. HttpClient httpClient = new DefaultHttpClient()
    20. try { HttpPut request = new HttpPut("http://yourAddressHere")
    21. StringEntity params =new StringEntity(jsonAddressArray.toString())
    22. request.setEntity(params)
    23. HttpResponse response = httpClient.execute(request)
    24. System.out.println(response.toString())
    25. // handle response here... }catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown()
    26. }}

    Positive Reactions
    1. Thanks, and it's good your pointing that out.
    2. But +1 for everything else!.
    3. I just put the values to my jsonAddressObj.
    4. I do not want to send harcoded values to any of the fields.
    5. "address": { "address1": "9100 hopkins bulvard hopkins bulvard bulvard", "address2": "6700 hopkins bulvard hopkins bulvard bulvard", "city": "HOPKINS", "county": "Scott", "postalCode": "55379", "state": "VA" } How do I accomplish this using JSONArray and JSONObject?
    Other Reactions
    1. OK.
    2. I need to send the following as http request.
    3. Yeh, I got the feeling we're not using the same library.
    4. I did take out the for loop.
    5. That helped me.
    6. I want the address to be fetched from the EditText.
    7. That is the reason i used txtAddress1.getText().toString().
    8. And mention that you're usign a different library, because he will ask why he can't have access to jsonAddressArray.add(jsonAddressObj);.
    9. Have you read anything about these technologies or checked the documentation?
    10. That did that work for me.
    11. Are you referring to a post or a put ?
    12. Is it just me or you're never adding anything to your jsonAddressArray ?
    13. Passed the jsonAddressObj to jsonObjSend.
    14. Http request is quite broad.
    15. I've uploaded the eclipse project to URL_https://dl.dropbox.com/u/6465647/InsertJsonExample.zip as I decided I'll make an online tutorial on my blog with this example.
    16. You should point that you have moved the JSONObject jsonAddressObj new JSONObject(); in the loop to create a new adress each time, because I don't think he will notice that.
    17. Here is what I want to do.
    18. it is a put method.
    19. Yeh your right...it's from the original code.

  • json object : Need to create a generic method to retrieve values

    Can we optimize it any further . . details

    Reactions - Positive 0, Negative 0, Others 0

    1. package javaapplication1
    2. import java.util.StringTokenizer
    3. import net.sf.json.JSONException
    4. import net.sf.json.JSONObject
    5. public class Tokenization {
    6. public static void main(String args[]) {
    7. JSONObject parentData = new JSONObject()
    8. JSONObject childData = new JSONObject()
    9. parentData.put("command", "dance")
    10. parentData.put("uid", "123123123")
    11. childData.put("uid", "007")
    12. childData.put("username", "sup")
    13. childData.put("password", "bros")
    14. parentData.put("params", childData)
    15. System.out.println(parentData)
    16. String result = getValue(parentData, "params.uid")
    17. System.out.println("Result:" + result)
    18. }
    19. public static String getValue(JSONObject inputJson, String field) {
    20. String resultValue = null
    21. try {
    22. StringTokenizer stJson = new StringTokenizer(field, ".")
    23. int count = stJson.countTokens()
    24. JSONObject objecStore = new JSONObject()
    25. objecStore = inputJson
    26. while (stJson.hasMoreTokens()) {
    27. String st = stJson.nextToken()
    28. if (count > 1) {
    29. JSONObject objNode = objecStore.getJSONObject(st)
    30. count--
    31. objecStore = objNode
    32. } else {
    33. System.out.println(st)
    34. resultValue = objecStore.getString(st)
    35. }
    36. }
    37. } catch (JSONException e) {
    38. }
    39. return resultValue
    40. }
    41. }

  • Retrieving all the keys in a nested json in java

    call the same function when your map.get(key).getClass()==JSONObject.Class. You can recursively traverse your JsonObject to get all keys.heres the pseudocode So suppose if your object is "a":1,"b":{"c":"hello","d":4.0}}the above function should give you "a","b","c","d" But if you want only "a","c","d" as your output,you can write . details

    Reactions - Positive 0, Negative 0, Others 0

    1. findKeys(JsonObject obj,List keys){List<String>keysFromObj=obj.keys()
    2. keys.addAll(keysFromObj)
    3. for(String key:keysFromObj){ if(obj.get(key).getClass()==JSONObject.class){ findKeys(obj.get(key),keys)
    4. } }}

  • Retrieving all the keys in a nested json in java

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. findKeys(JsonObject obj,List keys){List<String>keysFromObj=obj.keys()
    2. for(String key:keysFromObj){ if(obj.get(key).getClass()==JSONObject.class){ findKeys(obj.get(key),keys)
    3. }else{ keys.add(key)
    4. } }}

  • String to json conversion issue

    that is enough to do all the required things. Simple Example** First Prepare a String Now to parse the String Object U just have to pass the String to the constructor method That should do it and voila. details

    Reactions - Positive 3, Negative 6, Others 0

    1. JSONObject jObj = new JSONObject(jStr)

    Positive Reactions
    1. I just corrected it.
    2. I hope this helps.
    3. Thanks anyway for pointing that out.
    Negative Reactions
    1. Oh my bad!
    2. I just confused org.codehaus.jettison.json.JSONObject with net.sf.json.JSONObject .
    3. I'm realllly sorry!
    4. @David Grant is correct and I'm wrong.
    5. URL_http://json-lib.sourceforge.net/apidocs/jdk15/net/sf/json/JSONObject.html .
    6. Guys sorry for the wrong information.
    Other Reactions
    1. I take it back.
    2. -1: net.sf.json.JSONObject doesn't have a String constructor.

  • String to json conversion issue

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. import org.codehaus.jettison.json.JSONObject
    2. public static void run(JSONObject jsonObject) { System.out.println("in run-- "+jsonObject.getInt("person_id"))
    3. }public static void main(String[] args) throws Exception { System.out.println("here")
    4. String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}"
    5. JSONObject jsonObj = new JSONObject(json)
    6. run(jsonObj)
    7. }

  • String to json conversion issue

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. JSONObject()

  • WSO2 ESB Unable to convert complete JSON data to XML

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. package a.b.wso2
    2. import java.io.IOException
    3. import java.io.OutputStream
    4. import java.io.UnsupportedEncodingException
    5. import java.net.URL
    6. import net.sf.json.JSON
    7. import net.sf.json.xml.XMLSerializer
    8. import org.apache.axiom.om.OMElement
    9. import org.apache.axiom.om.OMOutputFormat
    10. import org.apache.axiom.om.util.AXIOMUtil
    11. import org.apache.axis2.AxisFault
    12. import org.apache.axis2.Constants
    13. import org.apache.axis2.context.MessageContext
    14. import org.apache.axis2.transport.MessageFormatter
    15. import org.apache.log4j.BasicConfigurator
    16. import org.apache.log4j.Logger
    17. public class WsoXtoJ implements MessageFormatter { Logger logger = Logger.getLogger("a.b.wso2converter")
    18. private static int counter=0
    19. public String convert(String xData) { counter++
    20. if (logger.isDebugEnabled()) { logger.debug("\n]]]]] (A"+counter+") converting xml\n " + xData + "\n-----")
    21. } try { String tran = "__ns__"
    22. XMLSerializer serializer = new XMLSerializer()
    23. OMElement e = AXIOMUtil.stringToOM(xData)
    24. OMElement b = (OMElement) e.getChildrenWithLocalName("Body").next()
    25. b = (OMElement) b.getChildElements().next()
    26. String xfrag = b.toStringWithConsume()
    27. String str = ""
    28. JSON j = serializer.read(xfrag)
    29. str = j.toString()
    30. String nstr = str.replaceAll("\"([a-zA-Z0-9_]+)" + tran + "([a-zA-Z0-9]+)\"(\\s*)(:)", "\"$1:$2\"$3:")
    31. //", "\"$1:$2\"")
    32. if (logger.isDebugEnabled()) { logger.debug("\n----- (A"+counter+") to json\n" + nstr+"\n[[[[[")
    33. } return nstr
    34. } catch (Exception e) { throw new RuntimeException(e)
    35. } } @Override public String formatSOAPAction(MessageContext msgCtxt, OMOutputFormat format, String soapActionString) { return null
    36. } @Override public byte[] getBytes(MessageContext ctx, OMOutputFormat format) throws AxisFault { String env=""
    37. try { OMElement element = ctx.getEnvelope().getBody().getFirstElement()
    38. String payload = this.convert(element.toString())
    39. return payload.getBytes(format.getCharSetEncoding())
    40. } catch (UnsupportedEncodingException e) { logger.error("(A"+counter+") error converting xml to json "+ctx.getEnvelope().toString())
    41. throw AxisFault.makeFault(e)
    42. } } @Override public String getContentType(MessageContext msgCtxt, OMOutputFormat format, String soapActionString) { String contentType = (String) msgCtxt.getProperty(Constants.Configuration.CONTENT_TYPE)
    43. String encoding = format.getCharSetEncoding()
    44. if (contentType == null) { contentType = (String) msgCtxt.getProperty(Constants.Configuration.MESSAGE_TYPE)
    45. } if (encoding != null) { contentType += "
    46. charset=" + encoding
    47. } return contentType
    48. } @Override public URL getTargetAddress(MessageContext msgCtxt, OMOutputFormat format, URL targetURL) throws AxisFault { return targetURL
    49. } @Override public void writeTo(MessageContext msgCtxt, OMOutputFormat format, OutputStream out, boolean preserve) throws AxisFault { try { out.write(this.getBytes(msgCtxt, format))
    50. out.flush()
    51. } catch (IOException e) { throw AxisFault.makeFault(e)
    52. } }}

  • WSO2 ESB Unable to convert complete JSON data to XML

    in this way we can smart proxy ie content route and mediate on transport and payload for ALL json based rest services through WSO2 with no issues This solves the problem I think camel does it this way by default). Here is the pom file and code place the jar into repository/components/lib you must update the messageformatter and messagebuilder mappings for content type application/json in axis2.xml . details

    Reactions - Positive 0, Negative 0, Others 0

    1. package a.b.wso2
    2. import java.io.InputStream
    3. import net.sf.json.JSON
    4. import net.sf.json.JSONSerializer
    5. import net.sf.json.xml.XMLSerializer
    6. import org.apache.axiom.om.OMElement
    7. import org.apache.axiom.om.util.AXIOMUtil
    8. import org.apache.axis2.AxisFault
    9. import org.apache.axis2.builder.Builder
    10. import org.apache.axis2.context.MessageContext
    11. import org.apache.commons.io.IOUtils
    12. import org.apache.log4j.Logger
    13. public class WsoJtoX implements Builder {
    14. Logger logger = Logger.getLogger("a.b.wso2converter")
    15. @Override
    16. public OMElement processDocument(
    17. InputStream is, String contentType, MessageContext messageContext) throws AxisFault {
    18. String jsonData = ""
    19. try {
    20. jsonData = IOUtils.toString(is, "UTF-8")
    21. String output = process(jsonData)
    22. OMElement e = AXIOMUtil.stringToOM(output)
    23. return e
    24. } catch (Exception e) {
    25. logger.error("error converting json string " + jsonData, e)
    26. if (e instanceof AxisFault) {
    27. throw (AxisFault) e
    28. }
    29. throw new AxisFault("(B" + counter + ") error converting json to xml", e)
    30. }
    31. }
    32. static int counter = 0
    33. public String process(String jsonData) throws AxisFault {
    34. try {
    35. String tran = "__ns__"
    36. jsonData = jsonData.replace("\r", "").trim()
    37. //jsonData=jsonData.replace("\n", "")
    38. String decoded =
    39. (jsonData.replaceAll(
    40. "\"([a-zA-Z0-9_]*)\\:([a-zA-Z0-9]*)\"(\\s*)(:)", "\"$1" + tran + "$2\"$3:"))
    41. counter++
    42. if (logger.isDebugEnabled()) {
    43. logger.debug("\n>>>>> (B" + counter + ") converting json\n " + jsonData + "\n====")
    44. }
    45. XMLSerializer serializer = new XMLSerializer()
    46. JSON json = JSONSerializer.toJSON(decoded)
    47. String xml = serializer.write(json)
    48. //add in the soap stuff StringBuilder sb = new StringBuilder()
    49. sb.append(
    50. "<soap:Envelope xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\"> <soap:Body>")
    51. sb.append(xml.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", ""))
    52. sb.append("</soap:Body></soap:Envelope>")
    53. if (logger.isDebugEnabled()) {
    54. logger.debug("\n==== (B" + counter + ") to xml\n" + sb.toString() + "\n<<<<<")
    55. }
    56. return sb.toString()
    57. } catch (Exception e) {
    58. throw new AxisFault("(B" + counter + ") error transforming json to xml", e)
    59. }
    60. }
    61. }

  • Create json object in servlet

    You need to add json-lib-2.4-jdk15.jar file to your project class-path and use following code to create JSON object. Console you will get output JSON data "key1":"value1","key2":"value2","key3":"value3" . details

    Reactions - Positive 0, Negative 0, Others 0

    1. JSONObject jsonData = new JSONObject()
    2. jsonData.put("key1", "value1")
    3. jsonData.put("key2", "value2")
    4. jsonData.put("key3", "value3")
    5. System.out.println("JSON data: "+jsonData.toString())

  • Create json object in servlet

    Your servlet returns only N number of JSON objects. But your giving that response to JSON array it may be the mistake try this code in your servlet . details

    Reactions - Positive 3, Negative 0, Others 0

    1. try{ Class.forName("com.mysql.jdbc.Driver").newInstance()
    2. Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/atmlivedetails","root","root")
    3. Statement st=con.createStatement()
    4. ResultSet rs=st.executeQuery("select atmbrno, atmbrname from location_stat where act_brname='"+br_id+"'")
    5. int i=0
    6. JSONArray jArray = new JSONArray()
    7. while(rs.next()){ String s = rs.getString("atmbrno")
    8. String t = rs.getString("atmbrname")
    9. JSONObject arrayObj = new JSONObject()
    10. arrayObj.put("atmbrno",s)
    11. arrayObj.put("atmbrname",t)
    12. jArray.add(i,arrayObj)
    13. i++
    14. } rs.close ()
    15. st.close ()
    16. out.print(jArray)
    17. }

    Positive Reactions
    1. Thanks @ColdHack I updated my answer.
    2. Wel done Bro...U r the best..it's working :D :D there is small thing wrong in ur code, jArray.put(i,arrayObj); and it should correct as jArray.add(i,arrayObj);Thanks again :D :D :D.
    3. ya i updated now thanks :).

  • Java OBJECT to JSONObject

    To add elements in this object we have used put method. Here is the full example code of FirstJSONJava.java is as follows To run this example you have to follow these few steps as follows Download JSON-lib jar and other supporting JarsAdd these jars to your classpathcreate and save FirstJSONJava.javaCompile it and execute Source Code . details

    Reactions - Positive 0, Negative 0, Others 0

    1. import net.sf.json.JSONObject
    2. public class FirstJSONJava {
    3. public static void main(String args[]) {
    4. JSONObject object = new JSONObject()
    5. object.put("name", "Amit Kumar")
    6. object.put("Max.Marks", new Integer(100))
    7. object.put("Min.Marks", new Double(40))
    8. object.put("Scored", new Double(66.67))
    9. object.put("nickname", "Amit")
    10. System.out.println(object)
    11. }
    12. }

  • Parsing non-standard JSON

    You can use Json.Net to parse your input string. You can even make use of dynamic as below with the help of this-extension-class Tested with your string With pure Json.Net . details

    Reactions - Positive 0, Negative 0, Others 0

    1. JObject jObj = (JObject)JsonConvert.DeserializeObject(json3)
    2. Console.WriteLine(jObj["names"]["en"])
    3. Console.WriteLine(jObj["status"])
    4. Console.WriteLine(jObj["start_time_xls"]["en"])
    5. Console.WriteLine(jObj["suspend_at"])

    Other Reactions
    1. @Stalker-Downvoter, Brave enough to explain your reason?

  • JSON/Java/Android: deserialisation from a String to a ArrayList<Strings>

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. package test
    2. import java.util.ArrayList
    3. import net.sf.json.JSONObject
    4. public class Tst {public static void main(String[] args) { ArrayList<String> versuch=new ArrayList<String>()
    5. for(int i=1
    6. i<11
    7. i++){ String temp = "Time1234"+i+",MeanValue123"+i+"
    8. "
    9. System.out.println(temp)
    10. versuch.add(temp)
    11. } System.out.println(versuch)
    12. JSONObject jSONString = new JSONObject()
    13. for (String string:versuch) { //put each string in DBdata to a JSON-Object with key=time and value=value jSONString.put(string.substring(0, string.indexOf(",")), string.substring(string.indexOf(",")+1,string.indexOf("
    14. ")))
    15. } String output="data.ID=1234."+jSONString.toString()
    16. System.out.println(output)
    17. System.out.println(JSONDeconstruct(output))
    18. } public static ArrayList<String> JSONDeconstruct (String st) { ArrayList<String> out=new ArrayList<String>()
    19. int begpos=st.indexOf("{")
    20. int endpos=st.indexOf("}")
    21. int index=0
    22. String work=st.substring(begpos+1, endpos)
    23. String replaced=work.replace("\",\"", ",")
    24. work=replaced.replace("\":\"", ":")
    25. replaced=work.replace("\"","")+",definedend"
    26. System.out.println(replaced)
    27. while (!replaced.equals("definedend")) { out.add(replaced.substring(0,replaced.indexOf(":"))+","+replaced.substring(replaced.indexOf(":")+1, replaced.indexOf(","))+"
    28. ")
    29. String tempstring=replaced.substring(replaced.indexOf(",")+1)
    30. replaced=tempstring
    31. index++
    32. System.out.println("loop disassembly step"+index+" "+replaced)
    33. } return out
    34. }}

  • Java json parsing exception

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. $ java com.so.Q8187623Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactoryat net.sf.json.AbstractJSON.<clinit>(AbstractJSON.java:53)at net.sf.json.util.CycleDetectionStrategy.<clinit>(CycleDetectionStrategy.java:36)at net.sf.json.JsonConfig.<clinit>(JsonConfig.java:65)at net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:84)at com.so.Q8187623.main(Q8187623.java:15)Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactoryat java.net.URLClassLoader$1.run(URLClassLoader.java:202)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(URLClassLoader.java:190)at java.lang.ClassLoader.loadClass(ClassLoader.java:306)at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)at java.lang.ClassLoader.loadClass(ClassLoader.java:247)... 5 more

  • Convert XML to JSON format

    None details

    Reactions - Positive 0, Negative 0, Others 0

    1. package xml2json
    2. import java.util.ArrayList
    3. import java.util.List
    4. import net.sf.json.*
    5. import org.xml.sax.*
    6. import org.xml.sax.helpers.DefaultHandler
    7. public class SAXJsonParser extends DefaultHandler {
    8. static final String TEXTKEY = "_text"
    9. JSONObject result
    10. List<JSONObject> stack
    11. public SAXJsonParser() {}
    12. public JSONObject getJson() {
    13. return result
    14. }
    15. public String attributeName(String name) {
    16. return "@" + name
    17. }
    18. public void startDocument() throws SAXException {
    19. stack = new ArrayList<JSONObject>()
    20. stack.add(0, new JSONObject())
    21. }
    22. public void endDocument() throws SAXException {
    23. result = stack.remove(0)
    24. }
    25. public void startElement(String uri, String localName, String qName, Attributes attributes)
    26. throws SAXException {
    27. JSONObject work = new JSONObject()
    28. for (int ix = 0 ix < attributes.getLength() ix++)
    29. work.put(attributeName(attributes.getLocalName(ix)), attributes.getValue(ix))
    30. stack.add(0, work)
    31. }
    32. public void endElement(String uri, String localName, String qName) throws SAXException {
    33. JSONObject pop = stack.remove(0)
    34. // examine stack Object stashable = pop
    35. if (pop.containsKey(TEXTKEY)) {
    36. String value = pop.getString(TEXTKEY).trim()
    37. if (pop.keySet().size() == 1) stashable = value
    38. // single value else if (StringUtils.isBlank(value)) pop.remove(TEXTKEY)
    39. }
    40. JSONObject parent = stack.get(0)
    41. if (!parent.containsKey(
    42. localName)) { // add new object parent.put( localName, stashable )
    43. } else { // aggregate into arrays Object work = parent.get(localName)
    44. if (work instanceof JSONArray) {
    45. ((JSONArray) work).add(stashable)
    46. } else {
    47. parent.put(localName, new JSONArray())
    48. parent.getJSONArray(localName).add(work)
    49. parent.getJSONArray(localName).add(stashable)
    50. }
    51. }
    52. }
    53. public void characters(char ch[], int start, int length) throws SAXException {
    54. JSONObject work = stack.get(0)
    55. // aggregate characters String value = (work.containsKey(TEXTKEY) ? work.getString(TEXTKEY) : "" )
    56. work.put(TEXTKEY, value + new String(ch, start, length))
    57. }
    58. public void warning(SAXParseException e) throws SAXException {
    59. System.out.println("warning e=" + e.getMessage())
    60. }
    61. public void error(SAXParseException e) throws SAXException {
    62. System.err.println("error e=" + e.getMessage())
    63. }
    64. public void fatalError(SAXParseException e) throws SAXException {
    65. System.err.println("fatalError e=" + e.getMessage())
    66. throw e
    67. }
    68. }

  • How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?

    you basically use certain classes in java like the ones defined here convert the final output to a json string and then send it to javascript there you convert the json string back to json using eval or probably using a library called json2.js and you are all set here is code for the same for more . ok First This can't compile you have a duplicate variable array Second create a servlet/Struts Action/etc that will contains the code that will create your array. details

    Reactions - Positive 0, Negative 1, Others 0

    1. ArrayList array=new ArrayList()
    2. array.add("D")
    3. array.add("A")
    4. array.add("L")
    5. JSONArray array = new JSONArray()

    Negative Reactions
    1. that was a typing mistake, i've edited.secondly, i'm stuck on how to send that JSON array as response to the be received and read by the following AJAX line:document.getElementById("txtHint").innerHTML=xmlhttp.responseText;could you give a simple example to start with?
    Other Reactions
    1. see the edit in my response.

  • How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?

    It will help you with the Ajax call and the transformation back to Json from the string received in the http response. Ex your ajax call should be like that with JQuery and your servlet should look like that . details

    Reactions - Positive 0, Negative 1, Others 0

    1. import java.io.*
    2. import javax.servlet.*
    3. import javax.servlet.http.*
    4. import net.sf.json.JSONArray
    5. public class JSONServlet extends HttpServlet {
    6. public void doGet(HttpServletRequest request, HttpServletResponse response)
    7. throws ServletException, IOException {
    8. JSONArray arrayObj = new JSONArray()
    9. arrayObj.add("D")
    10. arrayObj.add("A")
    11. arrayObj.add("L")
    12. arrayObj.add("D")
    13. arrayObj.add("A")
    14. arrayObj.add("TEST")
    15. PrintWriter out = response.getWriter()
    16. out.println(arrayObj)
    17. for (int i = 0 i < arrayObj.size() i++) {
    18. out.println(arrayObj.getString(i))
    19. }
    20. }
    21. }

    Negative Reactions
    1. that was a typing mistake, i've edited.secondly, i'm stuck on how to send that JSON array as response to the be received and read by the following AJAX line:document.getElementById("txtHint").innerHTML=xmlhttp.responseText;could you give a simple example to start with?
    Other Reactions
    1. see the edit in my response.

  • Call Google Maps API in a loop to geocode dozens of addresses and get "java.lang.String cannot be cast to net.sf.json.JSONObject"

    . It looks like your error might be happening at this line Looking at your query method it also seems like you are swallowing the JSONException and returning an empty string which then cannot be cast to a JSONobject**. details

    Reactions - Positive 0, Negative 0, Others 0

    1. JSONObject placemark = (JSONObject) query(json, "Placemark[0]")

  • Json object from database in java

    If you have a Device objects json lib can serialize the object using methods as JSON. Saved as JsonEncode.java Compiled with Executed with Note classpath has DOS separator) Dependencies json-lib-2.4-jdk15.jar commons-lang-2.6.jar commons-logging-1.1.1.jar commons-collections-3.2.1.jar commons-beanutils-1.8.0.jar ezmorph-1.0.6.jar . details

    Reactions - Positive 0, Negative 0, Others 0

    1. import java.util.*
    2. import net.sf.json.*
    3. public class JsonEncode {
    4. public static void main(String[] args) throws Exception {
    5. Device d1 = new Device("01", "CAM", "LivingRoom")
    6. Device d2 = new Device("15", "CAM", "Kitchen")
    7. List<Device> devices = new ArrayList<Device>(Arrays.asList(d1, d2))
    8. JSONArray serializedDevices = JSONArray.fromObject(devices)
    9. JSONObject jsonDevices = new JSONObject()
    10. jsonDevices.put("devices", serializedDevices)
    11. JSONObject json = new JSONObject()
    12. json.put("deviceList", jsonDevices)
    13. System.out.println(json)
    14. }
    15. public static class Device {
    16. Device(String id, String type, String name) {
    17. this.id = id
    18. this.type = type
    19. this.name = name
    20. }
    21. private String id
    22. public String getId() {
    23. return id
    24. }
    25. private String type
    26. public String getType() {
    27. return type
    28. }
    29. private String name
    30. public String getName() {
    31. return name
    32. }
    33. }
    34. }

  • Convert json string to Java Map(JSONLib)

    So it is a map. . details

    Reactions - Positive 1, Negative 1, Others 0

    1. import java.util.Map
    2. import net.sf.json.JSONObject
    3. public class Foo {
    4. static String json = "{\"one\":\"won\",\"two\":2,\"three\":false}"
    5. public static void main(String[] args) {
    6. JSONObject jsonObject = JSONObject.fromObject(json)
    7. Map map = jsonObject
    8. System.out.println(map)
    9. }
    10. }

    Positive Reactions
    1. Wow, haven't noticed this:) Thanks!.
    Negative Reactions
    1. If there's any interest in further decoupling the resulting Map from JSON-lib, note that it's trivial to create a new Map from an existing Map's entries using a copy constructor, such as Map map new HashMap(jsonObject);.
    Other Reactions
    1. What if the JSON is nested?

  • Parsing JSON in Spring MVC using Jackson JSON

    Your JSON has main-level Object with properties foo bar baz) and each property has different kind of value list string/boolean string/number). I'm using json lib from lib.sourceforge.net/ json-lib-2.1-jdk15.jar More samples here lib.sourceforge.net/usage.html . details

    Reactions - Positive 4, Negative 0, Others 0

    1. import net.sf.json.JSONObject
    2. ...public void send(){//put attributesMap m = New HashMap()
    3. m.put("send_to","my@admin.lan")
    4. m.put("email_subject","this is a test email")
    5. m.put("email_content","test email content")
    6. //generate JSON ObjectJSONObject json = JSONObject.fromObject(content)
    7. String message = json.toString()
    8. ...}public void receive(String jsonMessage){//parse attributesJSONObject json = JSONObject.fromObject(jsonMessage)
    9. String to = (String) json.get("send_to")
    10. String title = (String) json.get("email_subject")
    11. String content = (String) json.get("email_content")
    12. ...}

    Positive Reactions
    1. Sean, thanks anyway.
    2. Please: json-lib is very outdated.
    3. Jackson lib seems very cool.
    4. In my case, json-lib is enough.
    Other Reactions
    1. Use GSON or Jackson (which the OP explicitly mentioned).