Json string to JSONObject and JSONArray.

Source: Internet
Author: User

Specific conversion process

// JSONObject

String jsonMessage = "{\" \ ": \" 88 \ ", \" Mathematics \ ": \" 78 \ ", \" computer \": \ "99 \"}";
String value1 = null;
Try
{
// Convert a string to a jsonObject object
JSONObject myJsonObject = new JSONObject (jsonMessage );
// Obtain the corresponding value
Value1 = myJsonObject. getString ("Mathematics ");
}
Catch (JSONException e)
{
}
 
System. out. println ("value1 =" + value1 );

// JSONArray

JsonMessage = "[{'num': 'score ', 'foreign language': 88, 'hire': 65, 'geolocation ': 99, 'object': {'aaa ': '000000', 'bbb ': '000000', 'cccc': '000000'}, "+
"{'Num': 'interest ', 'foreign language': 28, 'hire': 45, 'geolocation ': 19, 'object': {'aaa ': '11a11', 'bbb ': '000000', 'cccc': '000000'}, "+
"{'Num': 'hobby ', 'foreign language': 48, 'hire': 62, 'geolocation ': 39, 'object': {'aaa ': '11c11', 'bbb ': '000000', 'cccc': '000000'}] ";
JSONArray myJsonArray;
Try
{
MyJsonArray = new JSONArray (jsonMessage );

For (int I = 0; I <myJsonArray. length (); I ++)
{
// Obtain every JsonObject
JSONObject myjObject = myJsonArray. getJSONObject (I );

// Obtain the value of each object
String numString = myjObject. getString ("num ");
Int englishScore = myjObject. getInt ("Foreign Language ");
Int historyScore = myjObject. getInt ("History ");
Int geographyScore = myjObject. getInt ("Geography ");
// Obtain the object of the object in the array
JSONObject myjObject2 = myjObject. getJSONObject ("object ");
String aaaString = myjObject2.getString ("aaa ");
System. out. println ("aaaString =" + aaaString );

System. out. println ("numString =" + numString );
System. out. println ("engishscore =" + engishscore );
System. out. println ("historyScore =" + historyScore );
System. out. println ("geographyScore =" + geographyScore );
}
}
Catch (JSONException e)
{
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.