欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

gson动态解析json

程序员文章站 2024-01-10 10:25:35
...
<!-- java版本 -->
public class TestEnty {
Map<String,Object> li;
}
package com.Company.Demo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.gson.Gson;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
private String json = "{li:{"temperature":"15","weather":"多云转晴","wind":"东北风微风","week":"星期日","date":"20151011"}}";

@Override 
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
Gson gson = new Gson(); 
TestEnty testEnty = gson.fromJson(json, TestEnty.class); 
Map<String, Object> li = testEnty.li; 

for (String key : li.keySet()) {
    Log.e("key", key); 
    Log.e("li.get(key).toString()", li.get(key).toString()); 
    }
  }
}


<!-- scala版本 -->

class TestEnty {
  var li :java.util.Map[String,Object] = null;
}
object App {
  
  def foo(x : Array[String]) = x.foldLeft("")((a,b) => a + b)

  def main(args : Array[String]) {
    import com.google.gson.Gson
    val json = "{li:{\"temperature\":\"15\",\"weather\":\"多云转晴\",\"wind\":\"东北风微风\",\"week\":\"星期日\",\"date\":\"20151011\"}}";
    val gson = new Gson
    val testEnty = gson.fromJson(json, classOf[TestEnty])
    val li = testEnty.li
    import scala.collection.JavaConverters._
    li.asScala.foreach(each=>{
      println(each._1+"  "+ each._2)
    })
  }
}

 

相关标签: 动态处理json